Merge branch 'release/3.0-preview3'
This commit is contained in:
commit
7fe3b7640d
|
|
@ -30,7 +30,7 @@
|
|||
OutputPath="$(ManifestsPath)aspnetcore-$(TargetRuntimeIdentifier)-$(PackageVersion).xml"
|
||||
BuildId="$(PackageVersion)"
|
||||
BuildData="Location=https://dotnet.myget.org/F/aspnetcore-dev/api/v3/index.json"
|
||||
RepoUri="$(BUILD_REPOSITORY_URI)"
|
||||
RepoUri="$(RepositoryUrl)"
|
||||
RepoBranch="$(BUILD_SOURCEBRANCH)"
|
||||
RepoCommit="$(BUILD_SOURCEVERSION)" />
|
||||
</Target>
|
||||
|
|
|
|||
|
|
@ -49,22 +49,6 @@ namespace Microsoft.AspNetCore.Blazor.Hosting.Test
|
|||
Assert.True(startup.ConfigureCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BrowserHost_StartAsync_SetsJSRuntime()
|
||||
{
|
||||
// Arrange
|
||||
var builder = new WebAssemblyHostBuilder();
|
||||
builder.UseBlazorStartup<MockStartup>();
|
||||
|
||||
var host = builder.Build();
|
||||
|
||||
// Act
|
||||
await host.StartAsync();
|
||||
|
||||
// Assert
|
||||
Assert.IsType<MonoWebAssemblyJSRuntime>(JSRuntime.Current);
|
||||
}
|
||||
|
||||
private class MockStartup : IBlazorStartup
|
||||
{
|
||||
public bool ConfigureCalled { get; set; }
|
||||
|
|
|
|||
|
|
@ -7,9 +7,9 @@ namespace Microsoft.AspNetCore.Blazor.E2EPerformance
|
|||
{
|
||||
public static class BenchmarkEvent
|
||||
{
|
||||
public static void Send(string name)
|
||||
public static void Send(IJSRuntime jsRuntime, string name)
|
||||
{
|
||||
((IJSInProcessRuntime)JSRuntime.Current).Invoke<object>(
|
||||
((IJSInProcessRuntime)jsRuntime).Invoke<object>(
|
||||
"receiveBenchmarkEvent",
|
||||
name);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,11 @@
|
|||
@page "/"
|
||||
@inject IJSRuntime JSRuntime
|
||||
|
||||
Hello, world!
|
||||
|
||||
@functions {
|
||||
protected override void OnAfterRender()
|
||||
{
|
||||
BenchmarkEvent.Send("Rendered index.cshtml");
|
||||
BenchmarkEvent.Send(JSRuntime, "Rendered index.cshtml");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
@page "/json"
|
||||
@inject IJSRuntime JSRuntime
|
||||
|
||||
<h2>JSON performance</h2>
|
||||
|
||||
|
|
@ -37,7 +38,7 @@
|
|||
|
||||
protected override void OnAfterRender()
|
||||
{
|
||||
BenchmarkEvent.Send("Finished JSON processing");
|
||||
BenchmarkEvent.Send(JSRuntime, "Finished JSON processing");
|
||||
}
|
||||
|
||||
string serializedValue;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
@page "/renderlist"
|
||||
@inject IJSRuntime JSRuntime
|
||||
|
||||
<h2>Render List</h2>
|
||||
|
||||
|
|
@ -47,7 +48,7 @@ Number of items: <input id="num-items" type="number" bind=@numItems />
|
|||
|
||||
protected override void OnAfterRender()
|
||||
{
|
||||
BenchmarkEvent.Send("Finished rendering list");
|
||||
BenchmarkEvent.Send(JSRuntime, "Finished rendering list");
|
||||
}
|
||||
|
||||
static IEnumerable<WeatherForecast> GenerateForecasts(int count)
|
||||
|
|
@ -71,4 +72,4 @@ Number of items: <input id="num-items" type="number" bind=@numItems />
|
|||
public int TemperatureF { get; set; }
|
||||
public string Summary { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ const selectValuePropname = '_blazorSelectValue';
|
|||
const sharedTemplateElemForParsing = document.createElement('template');
|
||||
const sharedSvgElemForParsing = document.createElementNS('http://www.w3.org/2000/svg', 'g');
|
||||
const preventDefaultEvents: { [eventType: string]: boolean } = { submit: true };
|
||||
const rootComponentsPendingFirstRender: { [componentId: number]: Element } = {};
|
||||
|
||||
export class BrowserRenderer {
|
||||
private eventDelegator: EventDelegator;
|
||||
|
|
@ -19,7 +20,9 @@ export class BrowserRenderer {
|
|||
}
|
||||
|
||||
public attachRootComponentToElement(componentId: number, element: Element) {
|
||||
this.attachComponentToElement(componentId, toLogicalElement(element));
|
||||
// 'allowExistingContents' to keep any prerendered content until we do the first client-side render
|
||||
this.attachComponentToElement(componentId, toLogicalElement(element, /* allowExistingContents */ true));
|
||||
rootComponentsPendingFirstRender[componentId] = element;
|
||||
}
|
||||
|
||||
public updateComponent(batch: RenderBatch, componentId: number, edits: ArraySegment<RenderTreeEdit>, referenceFrames: ArrayValues<RenderTreeFrame>) {
|
||||
|
|
@ -28,6 +31,13 @@ export class BrowserRenderer {
|
|||
throw new Error(`No element is currently associated with component ${componentId}`);
|
||||
}
|
||||
|
||||
// On the first render for each root component, clear any existing content (e.g., prerendered)
|
||||
const rootElementToClear = rootComponentsPendingFirstRender[componentId];
|
||||
if (rootElementToClear) {
|
||||
delete rootComponentsPendingFirstRender[componentId];
|
||||
clearElement(rootElementToClear);
|
||||
}
|
||||
|
||||
this.applyEdits(batch, element, 0, edits, referenceFrames);
|
||||
}
|
||||
|
||||
|
|
@ -368,3 +378,10 @@ function raiseEvent(event: Event, browserRendererId: number, eventHandlerId: num
|
|||
eventDescriptor,
|
||||
JSON.stringify(eventArgs.data));
|
||||
}
|
||||
|
||||
function clearElement(element: Element) {
|
||||
let childNode: Node | null;
|
||||
while (childNode = element.firstChild) {
|
||||
element.removeChild(childNode);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,9 +28,12 @@
|
|||
const logicalChildrenPropname = createSymbolOrFallback('_blazorLogicalChildren');
|
||||
const logicalParentPropname = createSymbolOrFallback('_blazorLogicalParent');
|
||||
|
||||
export function toLogicalElement(element: Element) {
|
||||
if (element.childNodes.length > 0) {
|
||||
throw new Error('New logical elements must start empty');
|
||||
export function toLogicalElement(element: Element, allowExistingContents?: boolean) {
|
||||
// Normally it's good to assert that the element has started empty, because that's the usual
|
||||
// situation and we probably have a bug if it's not. But for the element that contain prerendered
|
||||
// root components, we want to let them keep their content until we replace it.
|
||||
if (element.childNodes.length > 0 && !allowExistingContents) {
|
||||
throw new Error('New logical elements must start empty, or allowExistingContents must be true');
|
||||
}
|
||||
|
||||
element[logicalChildrenPropname] = [];
|
||||
|
|
|
|||
|
|
@ -16,7 +16,6 @@ export function attachRootComponentToElement(browserRendererId: number, elementS
|
|||
if (!browserRenderer) {
|
||||
browserRenderer = browserRenderers[browserRendererId] = new BrowserRenderer(browserRendererId);
|
||||
}
|
||||
clearElement(element);
|
||||
browserRenderer.attachRootComponentToElement(componentId, element);
|
||||
}
|
||||
|
||||
|
|
@ -57,10 +56,3 @@ export function renderBatch(browserRendererId: number, batch: RenderBatch) {
|
|||
browserRenderer.disposeEventHandler(eventHandlerId);
|
||||
}
|
||||
}
|
||||
|
||||
function clearElement(element: Element) {
|
||||
let childNode: Node | null;
|
||||
while (childNode = element.firstChild) {
|
||||
element.removeChild(childNode);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,75 @@
|
|||
// Copyright (c) .NET Foundation. All rights reserved.
|
||||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.AspNetCore.Components.Server;
|
||||
|
||||
namespace Microsoft.AspNetCore.Builder
|
||||
{
|
||||
/// <summary>
|
||||
/// Extensions for <see cref="IEndpointConventionBuilder"/>.
|
||||
/// </summary>
|
||||
public static class ComponentEndpointConventionBuilderExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Adds <typeparamref name="TComponent"/> to the list of components registered with this <see cref="ComponentHub"/> instance.
|
||||
/// </summary>
|
||||
/// <typeparam name="TComponent">The component type.</typeparam>
|
||||
/// <param name="builder">The <see cref="IEndpointConventionBuilder"/>.</param>
|
||||
/// <param name="selector">A CSS selector that identifies the DOM element into which the <typeparamref name="TComponent"/> will be placed.</param>
|
||||
/// <returns>The <paramref name="builder"/>.</returns>
|
||||
public static IEndpointConventionBuilder AddComponent<TComponent>(this IEndpointConventionBuilder builder, string selector)
|
||||
{
|
||||
if (builder == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(builder));
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(selector));
|
||||
}
|
||||
|
||||
return AddComponent(builder, typeof(TComponent), selector);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds <paramref name="componentType"/> to the list of components registered with this <see cref="ComponentHub"/> instance.
|
||||
/// The selector will default to the component name in lowercase.
|
||||
/// </summary>
|
||||
/// <param name="builder">The <see cref="IEndpointConventionBuilder"/>.</param>
|
||||
/// <param name="componentType">The component type.</param>
|
||||
/// <param name="selector">The component selector in the DOM for the <paramref name="componentType"/>.</param>
|
||||
/// <returns>The <paramref name="builder"/>.</returns>
|
||||
public static IEndpointConventionBuilder AddComponent(this IEndpointConventionBuilder builder, Type componentType, string selector)
|
||||
{
|
||||
if (builder == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(builder));
|
||||
}
|
||||
|
||||
if (componentType == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(componentType));
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(selector));
|
||||
}
|
||||
|
||||
builder.Add(endpointBuilder => AddComponent(endpointBuilder.Metadata, componentType, selector));
|
||||
return builder;
|
||||
}
|
||||
|
||||
private static void AddComponent(IList<object> metadata, Type type, string selector)
|
||||
{
|
||||
metadata.Add(new ComponentDescriptor
|
||||
{
|
||||
ComponentType = type,
|
||||
Selector = selector
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,110 @@
|
|||
// Copyright (c) .NET Foundation. All rights reserved.
|
||||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using System;
|
||||
using Microsoft.AspNetCore.Components.Server;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
|
||||
namespace Microsoft.AspNetCore.Builder
|
||||
{
|
||||
/// <summary>
|
||||
/// Extensions for <see cref="IEndpointRouteBuilder"/>.
|
||||
/// </summary>
|
||||
public static class ComponentEndpointRouteBuilderExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Maps the SignalR <see cref="ComponentHub"/> to the path <paramref name="path"/> and associates
|
||||
/// the component <typeparamref name="TComponent"/> to this hub instance as the given DOM <paramref name="selector"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TComponent">The first <see cref="IComponent"/> associated with this <see cref="ComponentHub"/>.</typeparam>
|
||||
/// <param name="routes">The <see cref="RouteBuilder"/>.</param>
|
||||
/// <param name="selector">The selector for the <typeparamref name="TComponent"/>.</param>
|
||||
/// <returns>The <see cref="IEndpointConventionBuilder"/>.</returns>
|
||||
public static IEndpointConventionBuilder MapComponentHub<TComponent>(
|
||||
this IEndpointRouteBuilder routes,
|
||||
string selector)
|
||||
{
|
||||
if (routes == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(routes));
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(selector));
|
||||
}
|
||||
|
||||
return routes.MapComponentHub(typeof(TComponent), selector, ComponentHub.DefaultPath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps the SignalR <see cref="ComponentHub"/> to the path <paramref name="path"/> and associates
|
||||
/// the component <typeparamref name="TComponent"/> to this hub instance as the given DOM <paramref name="selector"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TComponent">The first <see cref="IComponent"/> associated with this <see cref="ComponentHub"/>.</typeparam>
|
||||
/// <param name="routes">The <see cref="RouteBuilder"/>.</param>
|
||||
/// <param name="selector">The selector for the <typeparamref name="TComponent"/>.</param>
|
||||
/// <param name="path">The path to map to which the <see cref="ComponentHub"/> will be mapped.</param>
|
||||
/// <returns>The <see cref="IEndpointConventionBuilder"/>.</returns>
|
||||
public static IEndpointConventionBuilder MapComponentHub<TComponent>(
|
||||
this IEndpointRouteBuilder routes,
|
||||
string selector,
|
||||
string path)
|
||||
{
|
||||
if (routes == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(routes));
|
||||
}
|
||||
|
||||
if (path == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(path));
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(selector));
|
||||
}
|
||||
|
||||
return routes.MapComponentHub(typeof(TComponent), selector, path);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps the SignalR <see cref="ComponentHub"/> to the path <paramref name="path"/> and associates
|
||||
/// the component <paramref name="componentType"/> to this hub instance as the given DOM <paramref name="selector"/>.
|
||||
/// </summary>
|
||||
/// <param name="routes">The <see cref="RouteBuilder"/>.</param>
|
||||
/// <param name="componentType">The first <see cref="IComponent"/> associated with this <see cref="ComponentHub"/>.</param>
|
||||
/// <param name="selector">The selector for the <paramref name="componentType"/>.</param>
|
||||
/// <param name="path">The path to map to which the <see cref="ComponentHub"/> will be mapped.</param>
|
||||
/// <returns>The <see cref="IEndpointConventionBuilder"/>.</returns>
|
||||
public static IEndpointConventionBuilder MapComponentHub(
|
||||
this IEndpointRouteBuilder routes,
|
||||
Type componentType,
|
||||
string selector,
|
||||
string path)
|
||||
{
|
||||
if (routes == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(routes));
|
||||
}
|
||||
|
||||
if (path == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(path));
|
||||
}
|
||||
|
||||
if (componentType == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(componentType));
|
||||
}
|
||||
|
||||
if (selector == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(selector));
|
||||
}
|
||||
|
||||
return routes.MapHub<ComponentHub>(path).AddComponent(componentType, selector);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,91 +0,0 @@
|
|||
// Copyright (c) .NET Foundation. All rights reserved.
|
||||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using System;
|
||||
using Microsoft.AspNetCore.Components.Server;
|
||||
using Microsoft.AspNetCore.Components.Server.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.FileProviders;
|
||||
|
||||
namespace Microsoft.AspNetCore.Builder
|
||||
{
|
||||
/// <summary>
|
||||
/// Extension methods to configure an <see cref="IApplicationBuilder"/> for serving interactive components.
|
||||
/// </summary>
|
||||
public static class RazorComponentsApplicationBuilderExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Adds middleware for serving interactive Razor Components.
|
||||
/// </summary>
|
||||
/// <param name="builder">The <see cref="IApplicationBuilder"/>.</param>
|
||||
/// <typeparam name="TStartup">A components app startup type.</typeparam>
|
||||
/// <returns>The <see cref="IApplicationBuilder"/>.</returns>
|
||||
public static IApplicationBuilder UseRazorComponents<TStartup>(
|
||||
this IApplicationBuilder builder)
|
||||
{
|
||||
return UseRazorComponents<TStartup>(builder, null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds middleware for serving interactive Razor Components.
|
||||
/// </summary>
|
||||
/// <param name="builder">The <see cref="IApplicationBuilder"/>.</param>
|
||||
/// <param name="configure">A callback that can be used to configure the middleware.</param>
|
||||
/// <typeparam name="TStartup">A components app startup type.</typeparam>
|
||||
/// <returns>The <see cref="IApplicationBuilder"/>.</returns>
|
||||
public static IApplicationBuilder UseRazorComponents<TStartup>(
|
||||
this IApplicationBuilder builder,
|
||||
Action<RazorComponentsOptions> configure)
|
||||
{
|
||||
if (builder == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(builder));
|
||||
}
|
||||
|
||||
var options = new RazorComponentsOptions();
|
||||
configure?.Invoke(options);
|
||||
|
||||
// The use case for this flag is when developers want to add their own
|
||||
// SignalR middleware, e.g., when using Azure SignalR. By default we
|
||||
// add SignalR and BlazorHub automatically.
|
||||
if (options.UseSignalRWithBlazorHub)
|
||||
{
|
||||
builder.UseSignalR(route => route.MapHub<ComponentsHub>(ComponentsHub.DefaultPath));
|
||||
}
|
||||
|
||||
// Use embedded static content for /_framework
|
||||
builder.Map("/_framework", frameworkBuilder =>
|
||||
{
|
||||
UseFrameworkFiles(frameworkBuilder);
|
||||
});
|
||||
|
||||
// Use SPA fallback routing for anything else
|
||||
builder.UseSpa(spa => { });
|
||||
|
||||
return builder;
|
||||
}
|
||||
|
||||
private static void UseFrameworkFiles(IApplicationBuilder builder)
|
||||
{
|
||||
builder.UseStaticFiles(new StaticFileOptions
|
||||
{
|
||||
FileProvider = new ManifestEmbeddedFileProvider(
|
||||
typeof(RazorComponentsApplicationBuilderExtensions).Assembly,
|
||||
"frameworkFiles"),
|
||||
OnPrepareResponse = BlazorApplicationBuilderExtensions.SetCacheHeaders
|
||||
});
|
||||
|
||||
// TODO: Remove this
|
||||
// This is needed temporarily only until we implement a proper version
|
||||
// of library-embedded static resources for Razor Components apps.
|
||||
builder.Map("/blazor.boot.json", bootJsonBuilder =>
|
||||
{
|
||||
bootJsonBuilder.Use(async (ctx, next) =>
|
||||
{
|
||||
ctx.Response.ContentType = "application/json";
|
||||
await ctx.Response.WriteAsync(@"{ ""cssReferences"": [], ""jsReferences"": [] }");
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
// Copyright (c) .NET Foundation. All rights reserved.
|
||||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
|
||||
namespace Microsoft.AspNetCore.Components.Server.Builder
|
||||
{
|
||||
/// <summary>
|
||||
/// Specifies options to configure <see cref="RazorComponentsApplicationBuilderExtensions.UseRazorComponents{TStartup}(IApplicationBuilder)"/>
|
||||
/// </summary>
|
||||
public class RazorComponentsOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets a flag to indicate whether to attach middleware for
|
||||
/// communicating with interactive components via SignalR. Defaults
|
||||
/// to true.
|
||||
///
|
||||
/// If the value is set to false, the application must manually add
|
||||
/// SignalR middleware with <see cref="BlazorHub"/>.
|
||||
/// </summary>
|
||||
public bool UseSignalRWithBlazorHub { get; set; } = true;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,37 +0,0 @@
|
|||
// Copyright (c) .NET Foundation. All rights reserved.
|
||||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.AspNetCore.Components.Builder;
|
||||
|
||||
namespace Microsoft.AspNetCore.Components.Hosting
|
||||
{
|
||||
internal class ServerSideComponentsApplicationBuilder : IComponentsApplicationBuilder
|
||||
{
|
||||
public ServerSideComponentsApplicationBuilder(IServiceProvider services)
|
||||
{
|
||||
Services = services;
|
||||
Entries = new List<(Type componentType, string domElementSelector)>();
|
||||
}
|
||||
|
||||
public List<(Type componentType, string domElementSelector)> Entries { get; }
|
||||
|
||||
public IServiceProvider Services { get; }
|
||||
|
||||
public void AddComponent(Type componentType, string domElementSelector)
|
||||
{
|
||||
if (componentType == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(componentType));
|
||||
}
|
||||
|
||||
if (domElementSelector == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(domElementSelector));
|
||||
}
|
||||
|
||||
Entries.Add((componentType, domElementSelector));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -8,6 +8,10 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits
|
|||
{
|
||||
internal abstract class CircuitFactory
|
||||
{
|
||||
public abstract CircuitHost CreateCircuitHost(HttpContext httpContext, IClientProxy client);
|
||||
public abstract CircuitHost CreateCircuitHost(
|
||||
HttpContext httpContext,
|
||||
IClientProxy client,
|
||||
string uriAbsolute,
|
||||
string baseUriAbsolute);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,12 +2,12 @@
|
|||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Components.Browser;
|
||||
using Microsoft.AspNetCore.Components.Browser.Rendering;
|
||||
using Microsoft.AspNetCore.Components.Builder;
|
||||
using Microsoft.AspNetCore.Components.Hosting;
|
||||
using Microsoft.AspNetCore.Components.Rendering;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.JSInterop;
|
||||
|
|
@ -18,11 +18,10 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits
|
|||
{
|
||||
private static readonly AsyncLocal<CircuitHost> _current = new AsyncLocal<CircuitHost>();
|
||||
private readonly IServiceScope _scope;
|
||||
private readonly IDispatcher _dispatcher;
|
||||
private readonly CircuitHandler[] _circuitHandlers;
|
||||
private bool _initialized;
|
||||
|
||||
private Action<IComponentsApplicationBuilder> _configure;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current <see cref="Circuit"/>, if any.
|
||||
/// </summary>
|
||||
|
|
@ -53,17 +52,19 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits
|
|||
IClientProxy client,
|
||||
RendererRegistry rendererRegistry,
|
||||
RemoteRenderer renderer,
|
||||
Action<IComponentsApplicationBuilder> configure,
|
||||
IList<ComponentDescriptor> descriptors,
|
||||
IDispatcher dispatcher,
|
||||
IJSRuntime jsRuntime,
|
||||
CircuitHandler[] circuitHandlers)
|
||||
{
|
||||
_scope = scope ?? throw new ArgumentNullException(nameof(scope));
|
||||
Client = client ?? throw new ArgumentNullException(nameof(client));
|
||||
_dispatcher = dispatcher;
|
||||
Client = client;
|
||||
RendererRegistry = rendererRegistry ?? throw new ArgumentNullException(nameof(rendererRegistry));
|
||||
Descriptors = descriptors ?? throw new ArgumentNullException(nameof(descriptors));
|
||||
Renderer = renderer ?? throw new ArgumentNullException(nameof(renderer));
|
||||
_configure = configure ?? throw new ArgumentNullException(nameof(configure));
|
||||
JSRuntime = jsRuntime ?? throw new ArgumentNullException(nameof(jsRuntime));
|
||||
|
||||
|
||||
Services = scope.ServiceProvider;
|
||||
|
||||
Circuit = new Circuit(this);
|
||||
|
|
@ -77,7 +78,7 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits
|
|||
|
||||
public Circuit Circuit { get; }
|
||||
|
||||
public IClientProxy Client { get; }
|
||||
public IClientProxy Client { get; set; }
|
||||
|
||||
public IJSRuntime JSRuntime { get; }
|
||||
|
||||
|
|
@ -85,21 +86,29 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits
|
|||
|
||||
public RendererRegistry RendererRegistry { get; }
|
||||
|
||||
public IList<ComponentDescriptor> Descriptors { get; }
|
||||
|
||||
public IServiceProvider Services { get; }
|
||||
|
||||
public Task<IEnumerable<string>> PrerenderComponentAsync(Type componentType, ParameterCollection parameters)
|
||||
{
|
||||
return _dispatcher.InvokeAsync(async () =>
|
||||
{
|
||||
Renderer.StartPrerender();
|
||||
var result = await Renderer.RenderComponentAsync(componentType, parameters);
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
public async Task InitializeAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
await Renderer.InvokeAsync(async () =>
|
||||
{
|
||||
SetCurrentCircuitHost(this);
|
||||
|
||||
var builder = new ServerSideComponentsApplicationBuilder(Services);
|
||||
|
||||
_configure(builder);
|
||||
|
||||
for (var i = 0; i < builder.Entries.Count; i++)
|
||||
for (var i = 0; i < Descriptors.Count; i++)
|
||||
{
|
||||
var (componentType, domElementSelector) = builder.Entries[i];
|
||||
var (componentType, domElementSelector) = Descriptors[i];
|
||||
await Renderer.AddComponentAsync(componentType, domElementSelector);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,58 @@
|
|||
// Copyright (c) .NET Foundation. All rights reserved.
|
||||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Extensions;
|
||||
|
||||
namespace Microsoft.AspNetCore.Components.Server.Circuits
|
||||
{
|
||||
internal class CircuitPrerenderer : IComponentPrerenderer
|
||||
{
|
||||
private readonly CircuitFactory _circuitFactory;
|
||||
|
||||
public CircuitPrerenderer(CircuitFactory circuitFactory)
|
||||
{
|
||||
_circuitFactory = circuitFactory;
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<string>> PrerenderComponentAsync(ComponentPrerenderingContext prerenderingContext)
|
||||
{
|
||||
var context = prerenderingContext.Context;
|
||||
var circuitHost = _circuitFactory.CreateCircuitHost(
|
||||
context,
|
||||
client: null,
|
||||
GetFullUri(context.Request),
|
||||
GetFullBaseUri(context.Request));
|
||||
|
||||
// For right now we just do prerendering and dispose the circuit. In the future we will keep the circuit around and
|
||||
// reconnect to it from the ComponentsHub.
|
||||
try
|
||||
{
|
||||
return await circuitHost.PrerenderComponentAsync(
|
||||
prerenderingContext.ComponentType,
|
||||
prerenderingContext.Parameters);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await circuitHost.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private string GetFullUri(HttpRequest request)
|
||||
{
|
||||
return UriHelper.BuildAbsolute(
|
||||
request.Scheme,
|
||||
request.Host,
|
||||
request.PathBase,
|
||||
request.Path,
|
||||
request.QueryString);
|
||||
}
|
||||
|
||||
private string GetFullBaseUri(HttpRequest request)
|
||||
{
|
||||
return UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -2,49 +2,61 @@
|
|||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.Encodings.Web;
|
||||
using Microsoft.AspNetCore.Components.Browser;
|
||||
using Microsoft.AspNetCore.Components.Browser.Rendering;
|
||||
using Microsoft.AspNetCore.Components.Rendering;
|
||||
using Microsoft.AspNetCore.Components.Services;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.JSInterop;
|
||||
|
||||
namespace Microsoft.AspNetCore.Components.Server.Circuits
|
||||
{
|
||||
internal class DefaultCircuitFactory : CircuitFactory
|
||||
{
|
||||
private readonly IServiceScopeFactory _scopeFactory;
|
||||
private readonly DefaultCircuitFactoryOptions _options;
|
||||
private readonly ILoggerFactory _loggerFactory;
|
||||
|
||||
public DefaultCircuitFactory(
|
||||
IServiceScopeFactory scopeFactory,
|
||||
IOptions<DefaultCircuitFactoryOptions> options,
|
||||
ILoggerFactory loggerFactory)
|
||||
{
|
||||
if (options == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(options));
|
||||
}
|
||||
|
||||
_scopeFactory = scopeFactory ?? throw new ArgumentNullException(nameof(scopeFactory));
|
||||
_options = options.Value;
|
||||
_loggerFactory = loggerFactory;
|
||||
}
|
||||
|
||||
public override CircuitHost CreateCircuitHost(HttpContext httpContext, IClientProxy client)
|
||||
public override CircuitHost CreateCircuitHost(
|
||||
HttpContext httpContext,
|
||||
IClientProxy client,
|
||||
string uriAbsolute,
|
||||
string baseUriAbsolute)
|
||||
{
|
||||
if (!_options.StartupActions.TryGetValue(httpContext.Request.Path, out var config))
|
||||
{
|
||||
var message = $"Could not find an ASP.NET Core Components startup action for request path '{httpContext.Request.Path}'.";
|
||||
throw new InvalidOperationException(message);
|
||||
}
|
||||
var components = ResolveComponentMetadata(httpContext, client);
|
||||
|
||||
var scope = _scopeFactory.CreateScope();
|
||||
var jsRuntime = new RemoteJSRuntime(client);
|
||||
var encoder = scope.ServiceProvider.GetRequiredService<HtmlEncoder>();
|
||||
var jsRuntime = (RemoteJSRuntime)scope.ServiceProvider.GetRequiredService<IJSRuntime>();
|
||||
if (client != null)
|
||||
{
|
||||
jsRuntime.Initialize(client);
|
||||
}
|
||||
|
||||
var uriHelper = (RemoteUriHelper)scope.ServiceProvider.GetRequiredService<IUriHelper>();
|
||||
if (client != null)
|
||||
{
|
||||
uriHelper.Initialize(uriAbsolute, baseUriAbsolute, jsRuntime);
|
||||
}
|
||||
else
|
||||
{
|
||||
uriHelper.Initialize(uriAbsolute, baseUriAbsolute);
|
||||
}
|
||||
|
||||
var rendererRegistry = new RendererRegistry();
|
||||
var dispatcher = Renderer.CreateDefaultDispatcher();
|
||||
var renderer = new RemoteRenderer(
|
||||
|
|
@ -53,6 +65,7 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits
|
|||
jsRuntime,
|
||||
client,
|
||||
dispatcher,
|
||||
encoder,
|
||||
_loggerFactory.CreateLogger<RemoteRenderer>());
|
||||
|
||||
var circuitHandlers = scope.ServiceProvider.GetServices<CircuitHandler>()
|
||||
|
|
@ -64,15 +77,43 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits
|
|||
client,
|
||||
rendererRegistry,
|
||||
renderer,
|
||||
config,
|
||||
components,
|
||||
dispatcher,
|
||||
jsRuntime,
|
||||
circuitHandlers);
|
||||
|
||||
// Initialize per-circuit data that services need
|
||||
(circuitHost.Services.GetRequiredService<IJSRuntimeAccessor>() as DefaultJSRuntimeAccessor).JSRuntime = jsRuntime;
|
||||
// Initialize per - circuit data that services need
|
||||
(circuitHost.Services.GetRequiredService<ICircuitAccessor>() as DefaultCircuitAccessor).Circuit = circuitHost.Circuit;
|
||||
|
||||
return circuitHost;
|
||||
}
|
||||
|
||||
private static IList<ComponentDescriptor> ResolveComponentMetadata(HttpContext httpContext, IClientProxy client)
|
||||
{
|
||||
if (client == null)
|
||||
{
|
||||
// This is the prerendering case.
|
||||
return Array.Empty<ComponentDescriptor>();
|
||||
}
|
||||
else
|
||||
{
|
||||
var endpointFeature = httpContext.Features.Get<IEndpointFeature>();
|
||||
var endpoint = endpointFeature?.Endpoint;
|
||||
if (endpoint == null)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"{nameof(ComponentHub)} doesn't have an associated endpoint. " +
|
||||
"Use 'app.UseRouting(routes => routes.MapComponentHub<App>(\"app\"))' to register your hub.");
|
||||
}
|
||||
|
||||
var componentsMetadata = endpoint.Metadata.OfType<ComponentDescriptor>().ToList();
|
||||
if (componentsMetadata.Count == 0)
|
||||
{
|
||||
throw new InvalidOperationException("No component was registered with the component hub.");
|
||||
}
|
||||
|
||||
return componentsMetadata;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,18 +0,0 @@
|
|||
// Copyright (c) .NET Foundation. All rights reserved.
|
||||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.AspNetCore.Components.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Microsoft.AspNetCore.Components.Server
|
||||
{
|
||||
internal class DefaultCircuitFactoryOptions
|
||||
{
|
||||
// During the DI configuration phase, we use Configure<DefaultCircuitFactoryOptions>(...)
|
||||
// callbacks to build up this dictionary mapping paths to startup actions
|
||||
internal Dictionary<PathString, Action<IComponentsApplicationBuilder>> StartupActions { get; }
|
||||
= new Dictionary<PathString, Action<IComponentsApplicationBuilder>>();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
// Copyright (c) .NET Foundation. All rights reserved.
|
||||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using Microsoft.JSInterop;
|
||||
|
||||
namespace Microsoft.AspNetCore.Components.Server.Circuits
|
||||
{
|
||||
internal class DefaultJSRuntimeAccessor : IJSRuntimeAccessor
|
||||
{
|
||||
public IJSRuntime JSRuntime { get; set; }
|
||||
}
|
||||
}
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
// Copyright (c) .NET Foundation. All rights reserved.
|
||||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using Microsoft.JSInterop;
|
||||
|
||||
namespace Microsoft.AspNetCore.Components.Server.Circuits
|
||||
{
|
||||
internal interface IJSRuntimeAccessor
|
||||
{
|
||||
IJSRuntime JSRuntime { get; }
|
||||
}
|
||||
}
|
||||
|
|
@ -9,15 +9,23 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits
|
|||
{
|
||||
internal class RemoteJSRuntime : JSRuntimeBase
|
||||
{
|
||||
private readonly IClientProxy _clientProxy;
|
||||
private IClientProxy _clientProxy;
|
||||
|
||||
public RemoteJSRuntime(IClientProxy clientProxy)
|
||||
public RemoteJSRuntime()
|
||||
{
|
||||
}
|
||||
|
||||
internal void Initialize(IClientProxy clientProxy)
|
||||
{
|
||||
_clientProxy = clientProxy ?? throw new ArgumentNullException(nameof(clientProxy));
|
||||
}
|
||||
|
||||
protected override void BeginInvokeJS(long asyncHandle, string identifier, string argsJson)
|
||||
{
|
||||
if (_clientProxy == null)
|
||||
{
|
||||
throw new InvalidOperationException("The JavaScript runtime is not available during prerendering.");
|
||||
}
|
||||
_clientProxy.SendAsync("JS.BeginInvokeJS", asyncHandle, identifier, argsJson);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MessagePack;
|
||||
|
|
@ -15,20 +16,21 @@ using Microsoft.JSInterop;
|
|||
|
||||
namespace Microsoft.AspNetCore.Components.Browser.Rendering
|
||||
{
|
||||
internal class RemoteRenderer : Renderer
|
||||
internal class RemoteRenderer : HtmlRenderer
|
||||
{
|
||||
// The purpose of the timeout is just to ensure server resources are released at some
|
||||
// point if the client disconnects without sending back an ACK after a render
|
||||
private const int TimeoutMilliseconds = 60 * 1000;
|
||||
|
||||
private readonly int _id;
|
||||
private readonly IClientProxy _client;
|
||||
private IClientProxy _client;
|
||||
private readonly IJSRuntime _jsRuntime;
|
||||
private readonly RendererRegistry _rendererRegistry;
|
||||
private readonly ConcurrentDictionary<long, AutoCancelTaskCompletionSource<object>> _pendingRenders
|
||||
= new ConcurrentDictionary<long, AutoCancelTaskCompletionSource<object>>();
|
||||
private readonly ILogger _logger;
|
||||
private long _nextRenderId = 1;
|
||||
private bool _prerenderMode;
|
||||
|
||||
/// <summary>
|
||||
/// Notifies when a rendering exception occured.
|
||||
|
|
@ -49,8 +51,9 @@ namespace Microsoft.AspNetCore.Components.Browser.Rendering
|
|||
IJSRuntime jsRuntime,
|
||||
IClientProxy client,
|
||||
IDispatcher dispatcher,
|
||||
HtmlEncoder encoder,
|
||||
ILogger logger)
|
||||
: base(serviceProvider, dispatcher)
|
||||
: base(serviceProvider, encoder.Encode, dispatcher)
|
||||
{
|
||||
_rendererRegistry = rendererRegistry;
|
||||
_jsRuntime = jsRuntime;
|
||||
|
|
@ -97,6 +100,11 @@ namespace Microsoft.AspNetCore.Components.Browser.Rendering
|
|||
}
|
||||
}
|
||||
|
||||
internal void StartPrerender()
|
||||
{
|
||||
_prerenderMode = true;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
|
|
@ -107,6 +115,14 @@ namespace Microsoft.AspNetCore.Components.Browser.Rendering
|
|||
/// <inheritdoc />
|
||||
protected override Task UpdateDisplayAsync(in RenderBatch batch)
|
||||
{
|
||||
if (_prerenderMode)
|
||||
{
|
||||
// Nothing to do in prerender mode for right now.
|
||||
// In the future we will capture all the serialized render batches and
|
||||
// resend them to the client upon the initial reconnect.
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
// Note that we have to capture the data as a byte[] synchronously here, because
|
||||
// SignalR's SendAsync can wait an arbitrary duration before serializing the params.
|
||||
// The RenderBatch buffer will get reused by subsequent renders, so we need to
|
||||
|
|
|
|||
|
|
@ -14,15 +14,10 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits
|
|||
/// </summary>
|
||||
public class RemoteUriHelper : UriHelperBase
|
||||
{
|
||||
private readonly IJSRuntime _jsRuntime;
|
||||
private IJSRuntime _jsRuntime;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="RemoteUriHelper"/>.
|
||||
/// </summary>
|
||||
/// <param name="jsRuntime"></param>
|
||||
public RemoteUriHelper(IJSRuntime jsRuntime)
|
||||
public RemoteUriHelper()
|
||||
{
|
||||
_jsRuntime = jsRuntime;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -30,18 +25,38 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits
|
|||
/// </summary>
|
||||
/// <param name="uriAbsolute">The absolute URI of the current page.</param>
|
||||
/// <param name="baseUriAbsolute">The absolute base URI of the current page.</param>
|
||||
/// <param name="jsRuntime">The <see cref="IJSRuntime"/> to use for interoperability.</param>
|
||||
public void Initialize(string uriAbsolute, string baseUriAbsolute)
|
||||
{
|
||||
SetAbsoluteBaseUri(baseUriAbsolute);
|
||||
SetAbsoluteUri(uriAbsolute);
|
||||
TriggerOnLocationChanged();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the <see cref="RemoteUriHelper"/>.
|
||||
/// </summary>
|
||||
/// <param name="uriAbsolute">The absolute URI of the current page.</param>
|
||||
/// <param name="baseUriAbsolute">The absolute base URI of the current page.</param>
|
||||
/// <param name="jsRuntime">The <see cref="IJSRuntime"/> to use for interoperability.</param>
|
||||
public void Initialize(string uriAbsolute, string baseUriAbsolute, IJSRuntime jsRuntime)
|
||||
{
|
||||
if (_jsRuntime != null)
|
||||
{
|
||||
throw new InvalidOperationException("JavaScript runtime already initialized.");
|
||||
}
|
||||
|
||||
_jsRuntime = jsRuntime;
|
||||
|
||||
Initialize(uriAbsolute, baseUriAbsolute);
|
||||
|
||||
_jsRuntime.InvokeAsync<object>(
|
||||
Interop.EnableNavigationInterception,
|
||||
typeof(RemoteUriHelper).Assembly.GetName().Name,
|
||||
nameof(NotifyLocationChanged));
|
||||
Interop.EnableNavigationInterception,
|
||||
typeof(RemoteUriHelper).Assembly.GetName().Name,
|
||||
nameof(NotifyLocationChanged));
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// For framework use only.
|
||||
/// </summary>
|
||||
|
|
@ -61,9 +76,12 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits
|
|||
uriHelper.TriggerOnLocationChanged();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void NavigateToCore(string uri, bool forceLoad)
|
||||
{
|
||||
if (_jsRuntime == null)
|
||||
{
|
||||
throw new InvalidOperationException("Navigation is not allowed during prerendering.");
|
||||
}
|
||||
_jsRuntime.InvokeAsync<object>(Interop.NavigateTo, uri, forceLoad);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ namespace Microsoft.AspNetCore.Components.Server
|
|||
/// <summary>
|
||||
/// A SignalR hub that accepts connections to an ASP.NET Core Components application.
|
||||
/// </summary>
|
||||
public sealed class ComponentsHub : Hub
|
||||
public sealed class ComponentHub : Hub
|
||||
{
|
||||
private static readonly object CircuitKey = new object();
|
||||
private readonly CircuitFactory _circuitFactory;
|
||||
|
|
@ -25,7 +25,7 @@ namespace Microsoft.AspNetCore.Components.Server
|
|||
/// Intended for framework use only. Applications should not instantiate
|
||||
/// this class directly.
|
||||
/// </summary>
|
||||
public ComponentsHub(IServiceProvider services, ILogger<ComponentsHub> logger)
|
||||
public ComponentHub(IServiceProvider services, ILogger<ComponentHub> logger)
|
||||
{
|
||||
_circuitFactory = services.GetRequiredService<CircuitFactory>();
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
|
|
@ -58,11 +58,13 @@ namespace Microsoft.AspNetCore.Components.Server
|
|||
/// </summary>
|
||||
public async Task StartCircuit(string uriAbsolute, string baseUriAbsolute)
|
||||
{
|
||||
var circuitHost = _circuitFactory.CreateCircuitHost(Context.GetHttpContext(), Clients.Caller);
|
||||
circuitHost.UnhandledException += CircuitHost_UnhandledException;
|
||||
var circuitHost = _circuitFactory.CreateCircuitHost(
|
||||
Context.GetHttpContext(),
|
||||
Clients.Caller,
|
||||
uriAbsolute,
|
||||
baseUriAbsolute);
|
||||
|
||||
var uriHelper = (RemoteUriHelper)circuitHost.Services.GetRequiredService<IUriHelper>();
|
||||
uriHelper.Initialize(uriAbsolute, baseUriAbsolute);
|
||||
circuitHost.UnhandledException += CircuitHost_UnhandledException;
|
||||
|
||||
// If initialization fails, this will throw. The caller will fail if they try to call into any interop API.
|
||||
await circuitHost.InitializeAsync(Context.ConnectionAborted);
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
// Copyright (c) .NET Foundation. All rights reserved.
|
||||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using System;
|
||||
|
||||
namespace Microsoft.AspNetCore.Components.Server
|
||||
{
|
||||
internal class ComponentDescriptor
|
||||
{
|
||||
public Type ComponentType { get; set; }
|
||||
|
||||
public string Selector { get; set; }
|
||||
|
||||
public void Deconstruct(out Type componentType, out string selector)
|
||||
{
|
||||
componentType = ComponentType;
|
||||
selector = Selector;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
// Copyright (c) .NET Foundation. All rights reserved.
|
||||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Components.Server;
|
||||
using Microsoft.AspNetCore.Components.Server.Circuits;
|
||||
using Microsoft.AspNetCore.Components.Services;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.JSInterop;
|
||||
|
||||
namespace Microsoft.Extensions.DependencyInjection
|
||||
{
|
||||
/// <summary>
|
||||
/// Extension methods to configure an <see cref="IServiceCollection"/> for components.
|
||||
/// </summary>
|
||||
public static class ComponentServiceCollectionExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Adds Razor Component app services to the service collection.
|
||||
/// </summary>
|
||||
/// <param name="services">The <see cref="IServiceCollection"/>.</param>
|
||||
/// <returns>The <see cref="IServiceCollection"/>.</returns>
|
||||
public static IServiceCollection AddRazorComponents(this IServiceCollection services)
|
||||
{
|
||||
services.AddSignalR().AddMessagePackProtocol();
|
||||
|
||||
// Here we add a bunch of services that don't vary in any way based on the
|
||||
// user's configuration. So even if the user has multiple independent server-side
|
||||
// Components entrypoints, this lot is the same and repeated registrations are a no-op.
|
||||
services.TryAddEnumerable(ServiceDescriptor.Singleton<IPostConfigureOptions<StaticFileOptions>, ConfigureStaticFilesOptions>());
|
||||
services.TryAddSingleton<CircuitFactory, DefaultCircuitFactory>();
|
||||
services.TryAddScoped(s => s.GetRequiredService<ICircuitAccessor>().Circuit);
|
||||
services.TryAddScoped<ICircuitAccessor, DefaultCircuitAccessor>();
|
||||
|
||||
// We explicitly take over the prerendering and components services here.
|
||||
// We can't have two separate component implementations coexisting at the
|
||||
// same time, so when you register components (Circuits) it takes over
|
||||
// all the abstractions.
|
||||
services.AddScoped<IComponentPrerenderer, CircuitPrerenderer>();
|
||||
|
||||
// Standard razor component services implementations
|
||||
services.AddScoped<IUriHelper, RemoteUriHelper>();
|
||||
services.AddScoped<IJSRuntime, RemoteJSRuntime>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,115 @@
|
|||
// Copyright (c) .NET Foundation. All rights reserved.
|
||||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.StaticFiles;
|
||||
using Microsoft.Extensions.FileProviders;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.Extensions.Primitives;
|
||||
|
||||
namespace Microsoft.AspNetCore.Components.Server
|
||||
{
|
||||
internal class ConfigureStaticFilesOptions : IPostConfigureOptions<StaticFileOptions>
|
||||
{
|
||||
public ConfigureStaticFilesOptions(IWebHostEnvironment environment)
|
||||
{
|
||||
Environment = environment;
|
||||
}
|
||||
|
||||
public IWebHostEnvironment Environment { get; }
|
||||
|
||||
public void PostConfigure(string name, StaticFileOptions options)
|
||||
{
|
||||
name = name ?? throw new ArgumentNullException(nameof(name));
|
||||
options = options ?? throw new ArgumentNullException(nameof(options));
|
||||
|
||||
if (name != Options.DefaultName)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Basic initialization in case the options weren't initialized by any other component
|
||||
options.ContentTypeProvider = options.ContentTypeProvider ?? new FileExtensionContentTypeProvider();
|
||||
if (options.FileProvider == null && Environment.WebRootFileProvider == null)
|
||||
{
|
||||
throw new InvalidOperationException("Missing FileProvider.");
|
||||
}
|
||||
|
||||
options.FileProvider = options.FileProvider ?? Environment.WebRootFileProvider;
|
||||
|
||||
var prepareResponse = options.OnPrepareResponse;
|
||||
if (prepareResponse == null)
|
||||
{
|
||||
options.OnPrepareResponse = BlazorApplicationBuilderExtensions.SetCacheHeaders;
|
||||
}
|
||||
else
|
||||
{
|
||||
void PrepareResponse(StaticFileResponseContext context)
|
||||
{
|
||||
prepareResponse(context);
|
||||
BlazorApplicationBuilderExtensions.SetCacheHeaders(context);
|
||||
}
|
||||
|
||||
options.OnPrepareResponse = PrepareResponse;
|
||||
}
|
||||
|
||||
// Add our provider
|
||||
var provider = new ManifestEmbeddedFileProvider(typeof(ConfigureStaticFilesOptions).Assembly);
|
||||
|
||||
options.FileProvider = new CompositeFileProvider(provider, new ContentReferencesFileProvider(), options.FileProvider);
|
||||
}
|
||||
|
||||
private class ContentReferencesFileProvider : IFileProvider
|
||||
{
|
||||
byte[] _data = Encoding.UTF8.GetBytes(@"{ ""cssReferences"": [], ""jsReferences"": [] }");
|
||||
|
||||
public IDirectoryContents GetDirectoryContents(string subpath)
|
||||
{
|
||||
return new NotFoundDirectoryContents();
|
||||
}
|
||||
|
||||
public IFileInfo GetFileInfo(string subpath)
|
||||
{
|
||||
if (subpath.Equals("/_framework/blazor.boot.json", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return new MemoryFileInfo(_data);
|
||||
}
|
||||
|
||||
return new NotFoundFileInfo(subpath);
|
||||
}
|
||||
|
||||
public IChangeToken Watch(string filter) => NullChangeToken.Singleton;
|
||||
|
||||
private class MemoryFileInfo : IFileInfo
|
||||
{
|
||||
private readonly byte[] _data;
|
||||
|
||||
public MemoryFileInfo(byte[] data)
|
||||
{
|
||||
_data = data;
|
||||
}
|
||||
|
||||
public bool Exists => true;
|
||||
|
||||
public long Length => _data.Length;
|
||||
|
||||
public string PhysicalPath => "/_framework/blazor.boot.json";
|
||||
|
||||
public string Name => "blazor.boot.json";
|
||||
|
||||
public DateTimeOffset LastModified => DateTimeOffset.FromUnixTimeSeconds(0);
|
||||
|
||||
public bool IsDirectory => false;
|
||||
|
||||
public Stream CreateReadStream()
|
||||
{
|
||||
return new MemoryStream(_data, writable: false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,115 +0,0 @@
|
|||
// Copyright (c) .NET Foundation. All rights reserved.
|
||||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using System;
|
||||
using Microsoft.AspNetCore.Components.Hosting;
|
||||
using Microsoft.AspNetCore.Components.Server;
|
||||
using Microsoft.AspNetCore.Components.Server.Circuits;
|
||||
using Microsoft.AspNetCore.Components.Services;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
|
||||
namespace Microsoft.Extensions.DependencyInjection
|
||||
{
|
||||
/// <summary>
|
||||
/// Extension methods to configure an <see cref="IServiceCollection"/> for interactive components.
|
||||
/// </summary>
|
||||
public static class RazorComponentsServiceCollectionExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Adds Razor Component services to the service collection.
|
||||
/// </summary>
|
||||
/// <param name="services">The <see cref="IServiceCollection"/>.</param>
|
||||
/// <param name="startupType">A Razor Components project startup type.</param>
|
||||
/// <returns>The <see cref="IServiceCollection"/>.</returns>
|
||||
public static IServiceCollection AddRazorComponents(
|
||||
this IServiceCollection services,
|
||||
Type startupType)
|
||||
{
|
||||
if (services == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(services));
|
||||
}
|
||||
|
||||
if (startupType == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(startupType));
|
||||
}
|
||||
|
||||
return AddRazorComponentsCore(services, startupType);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds Razor Component app services to the service collection.
|
||||
/// </summary>
|
||||
/// <param name="services">The <see cref="IServiceCollection"/>.</param>
|
||||
/// <typeparam name="TStartup">A Components app startup type.</typeparam>
|
||||
/// <returns>The <see cref="IServiceCollection"/>.</returns>
|
||||
public static IServiceCollection AddRazorComponents<TStartup>(
|
||||
this IServiceCollection services)
|
||||
{
|
||||
if (services == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(services));
|
||||
}
|
||||
|
||||
return AddRazorComponentsCore(services, typeof(TStartup));
|
||||
}
|
||||
|
||||
private static IServiceCollection AddRazorComponentsCore(
|
||||
IServiceCollection services,
|
||||
Type startupType)
|
||||
{
|
||||
AddStandardRazorComponentsServices(services);
|
||||
|
||||
if (startupType != null)
|
||||
{
|
||||
// Call TStartup's ConfigureServices method immediately
|
||||
var startup = Activator.CreateInstance(startupType);
|
||||
var wrapper = new ConventionBasedStartup(startup);
|
||||
wrapper.ConfigureServices(services);
|
||||
|
||||
// Configure the circuit factory to call a startup action when each
|
||||
// incoming connection is established. The startup action is "call
|
||||
// TStartup's Configure method".
|
||||
services.Configure<DefaultCircuitFactoryOptions>(circuitFactoryOptions =>
|
||||
{
|
||||
var endpoint = ComponentsHub.DefaultPath; // TODO: allow configuring this
|
||||
if (circuitFactoryOptions.StartupActions.ContainsKey(endpoint))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"Multiple Components app entries are configured to use " +
|
||||
$"the same endpoint '{endpoint}'.");
|
||||
}
|
||||
|
||||
circuitFactoryOptions.StartupActions.Add(endpoint, builder =>
|
||||
{
|
||||
wrapper.Configure(builder, builder.Services);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
private static void AddStandardRazorComponentsServices(IServiceCollection services)
|
||||
{
|
||||
// Here we add a bunch of services that don't vary in any way based on the
|
||||
// user's configuration. So even if the user has multiple independent server-side
|
||||
// Components entrypoints, this lot is the same and repeated registrations are a no-op.
|
||||
services.TryAddSingleton<CircuitFactory, DefaultCircuitFactory>();
|
||||
services.TryAddScoped<ICircuitAccessor, DefaultCircuitAccessor>();
|
||||
services.TryAddScoped(s => s.GetRequiredService<ICircuitAccessor>().Circuit);
|
||||
services.TryAddScoped<IJSRuntimeAccessor, DefaultJSRuntimeAccessor>();
|
||||
services.TryAddScoped(s => s.GetRequiredService<IJSRuntimeAccessor>().JSRuntime);
|
||||
services.TryAddScoped<IUriHelper, RemoteUriHelper>();
|
||||
|
||||
// We've discussed with the SignalR team and believe it's OK to have repeated
|
||||
// calls to AddSignalR (making the nonfirst ones no-ops). If we want to change
|
||||
// this in the future, we could change AddComponents to be an extension
|
||||
// method on ISignalRServerBuilder so the developer always has to chain it onto
|
||||
// their own AddSignalR call. For now we're keeping it like this because it's
|
||||
// simpler for developers in common cases.
|
||||
services.AddSignalR().AddMessagePackProtocol();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netcoreapp3.0</TargetFramework>
|
||||
|
|
@ -31,7 +31,7 @@
|
|||
<ItemGroup Condition="'$(BuildNodeJS)' != 'false'">
|
||||
<!-- We need .Browser.JS to build first so we can embed its .js output -->
|
||||
<ProjectReference Include="..\..\Browser.JS\src\Microsoft.AspNetCore.Components.Browser.JS.npmproj" ReferenceOutputAssembly="false" />
|
||||
<EmbeddedResource Include="..\..\Browser.JS\src\dist\components.server.js" LogicalName="frameworkFiles\%(Filename)%(Extension)" />
|
||||
<EmbeddedResource Include="..\..\Browser.JS\src\dist\components.server.js" LogicalName="_framework\%(Filename)%(Extension)" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -2,10 +2,13 @@
|
|||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Components.Browser;
|
||||
using Microsoft.AspNetCore.Components.Browser.Rendering;
|
||||
using Microsoft.AspNetCore.Components.Rendering;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
|
@ -22,7 +25,7 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits
|
|||
{
|
||||
// Arrange
|
||||
var serviceScope = new Mock<IServiceScope>();
|
||||
var remoteRenderer = GetRemoteRenderer();
|
||||
var remoteRenderer = GetRemoteRenderer(Renderer.CreateDefaultDispatcher());
|
||||
var circuitHost = GetCircuitHost(
|
||||
serviceScope.Object,
|
||||
remoteRenderer);
|
||||
|
|
@ -130,8 +133,8 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits
|
|||
var clientProxy = Mock.Of<IClientProxy>();
|
||||
var renderRegistry = new RendererRegistry();
|
||||
var jsRuntime = Mock.Of<IJSRuntime>();
|
||||
|
||||
remoteRenderer = remoteRenderer ?? GetRemoteRenderer();
|
||||
var dispatcher = Renderer.CreateDefaultDispatcher();
|
||||
remoteRenderer = remoteRenderer ?? GetRemoteRenderer(dispatcher);
|
||||
handlers = handlers ?? Array.Empty<CircuitHandler>();
|
||||
|
||||
return new CircuitHost(
|
||||
|
|
@ -139,24 +142,26 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits
|
|||
clientProxy,
|
||||
renderRegistry,
|
||||
remoteRenderer,
|
||||
configure: _ => { },
|
||||
new List<ComponentDescriptor>(),
|
||||
dispatcher,
|
||||
jsRuntime: jsRuntime,
|
||||
handlers);
|
||||
}
|
||||
|
||||
private static TestRemoteRenderer GetRemoteRenderer()
|
||||
private static TestRemoteRenderer GetRemoteRenderer(IDispatcher dispatcher)
|
||||
{
|
||||
return new TestRemoteRenderer(
|
||||
Mock.Of<IServiceProvider>(),
|
||||
new RendererRegistry(),
|
||||
dispatcher,
|
||||
Mock.Of<IJSRuntime>(),
|
||||
Mock.Of<IClientProxy>());
|
||||
}
|
||||
|
||||
private class TestRemoteRenderer : RemoteRenderer
|
||||
{
|
||||
public TestRemoteRenderer(IServiceProvider serviceProvider, RendererRegistry rendererRegistry, IJSRuntime jsRuntime, IClientProxy client)
|
||||
: base(serviceProvider, rendererRegistry, jsRuntime, client, CreateDefaultDispatcher(), NullLogger.Instance)
|
||||
public TestRemoteRenderer(IServiceProvider serviceProvider, RendererRegistry rendererRegistry, IDispatcher dispatcher, IJSRuntime jsRuntime, IClientProxy client)
|
||||
: base(serviceProvider, rendererRegistry, jsRuntime, client, dispatcher, HtmlEncoder.Default, NullLogger.Instance)
|
||||
{
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -126,7 +126,7 @@ namespace Microsoft.AspNetCore.Components.E2ETest.Infrastructure
|
|||
output = builder.ToString();
|
||||
}
|
||||
|
||||
throw new InvalidOperationException($"Failed to start selenium sever. {Environment.NewLine}{output}", ex.GetBaseException());
|
||||
throw new InvalidOperationException($"Failed to start selenium sever. {System.Environment.NewLine}{output}", ex.GetBaseException());
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -5,9 +5,9 @@
|
|||
</div>
|
||||
|
||||
<div class="main">
|
||||
<div class="top-row px-4">
|
||||
@*<div class="top-row px-4">
|
||||
<a href="http://blazor.net" target="_blank" class="ml-md-auto">About</a>
|
||||
</div>
|
||||
</div>*@
|
||||
|
||||
<div class="content px-4">
|
||||
@Body
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@
|
|||
|
||||
<ItemGroup>
|
||||
<Reference Include="Microsoft.AspNetCore.Components.Server" />
|
||||
<Reference Include="Microsoft.AspNetCore.Mvc" />
|
||||
<ProjectReference Include="..\ComponentsApp.App\ComponentsApp.App.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,6 @@
|
|||
@page "{*clientroutes}"
|
||||
@using ComponentsApp.App
|
||||
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
|
|
@ -9,7 +12,7 @@
|
|||
<link href="css/site.css" rel="stylesheet" />
|
||||
</head>
|
||||
<body>
|
||||
<app>Loading...</app>
|
||||
<app>@(await Html.RenderComponentAsync<App>())</app>
|
||||
|
||||
<script src="_framework/components.server.js"></script>
|
||||
</body>
|
||||
|
|
@ -14,8 +14,10 @@ namespace ComponentsApp.Server
|
|||
{
|
||||
public void ConfigureServices(IServiceCollection services)
|
||||
{
|
||||
services.AddMvc();
|
||||
services.AddSingleton<CircuitHandler, LoggingCircuitHandler>();
|
||||
services.AddRazorComponents<App.Startup>();
|
||||
services.AddRazorComponents();
|
||||
|
||||
services.AddSingleton<WeatherForecastService, DefaultWeatherForecastService>();
|
||||
}
|
||||
|
||||
|
|
@ -27,7 +29,11 @@ namespace ComponentsApp.Server
|
|||
}
|
||||
|
||||
app.UseStaticFiles();
|
||||
app.UseRazorComponents<App.Startup>();
|
||||
app.UseRouting(builder =>
|
||||
{
|
||||
builder.MapRazorPages();
|
||||
builder.MapComponentHub<App.App>("app");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
using Microsoft.AspNetCore.Components.Server;
|
||||
using BasicTestApp;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Components.Server;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
|
|
@ -24,7 +26,7 @@ namespace TestServer
|
|||
{
|
||||
options.AddPolicy("AllowAll", _ => { /* Controlled below */ });
|
||||
});
|
||||
services.AddRazorComponents<BasicTestApp.Startup>();
|
||||
services.AddRazorComponents();
|
||||
}
|
||||
|
||||
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
|
||||
|
|
@ -47,8 +49,12 @@ namespace TestServer
|
|||
// we're not relying on any extra magic inside UseServerSideBlazor, since it's
|
||||
// important that people can set up these bits of middleware manually (e.g., to
|
||||
// swap in UseAzureSignalR instead of UseSignalR).
|
||||
subdirApp.UseSignalR(route => route.MapHub<ComponentsHub>(ComponentsHub.DefaultPath));
|
||||
subdirApp.UseBlazor<BasicTestApp.Startup>();
|
||||
subdirApp.UseRouting(routes =>
|
||||
routes.MapHub<ComponentHub>(ComponentHub.DefaultPath).AddComponent<Index>(selector: "root"));
|
||||
|
||||
subdirApp.MapWhen(
|
||||
ctx => ctx.Features.Get<IEndpointFeature>()?.Endpoint == null,
|
||||
blazorBuilder => blazorBuilder.UseBlazor<BasicTestApp.Startup>());
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -7,8 +7,12 @@ namespace Microsoft.AspNetCore.Hosting
|
|||
{
|
||||
/// <summary>
|
||||
/// Allows consumers to perform cleanup during a graceful shutdown.
|
||||
/// <para>
|
||||
/// This type is obsolete and will be removed in a future version.
|
||||
/// The recommended alternative is Microsoft.Extensions.Hosting.IHostApplicationLifetime.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
[System.Obsolete("Use Microsoft.Extensions.Hosting.IHostApplicationLifetime instead.", error: false)]
|
||||
[System.Obsolete("This type is obsolete and will be removed in a future version. The recommended alternative is Microsoft.Extensions.Hosting.IHostApplicationLifetime.", error: false)]
|
||||
public interface IApplicationLifetime
|
||||
{
|
||||
/// <summary>
|
||||
|
|
|
|||
|
|
@ -7,8 +7,12 @@ namespace Microsoft.AspNetCore.Hosting
|
|||
{
|
||||
/// <summary>
|
||||
/// Provides information about the web hosting environment an application is running in.
|
||||
/// <para>
|
||||
/// This type is obsolete and will be removed in a future version.
|
||||
/// The recommended alternative is Microsoft.AspNetCore.Hosting.IWebHostEnvironment.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
[System.Obsolete("Use IWebHostEnvironment instead.", error: false)]
|
||||
[System.Obsolete("This type is obsolete and will be removed in a future version. The recommended alternative is Microsoft.AspNetCore.Hosting.IWebHostEnvironment.", error: false)]
|
||||
public interface IHostingEnvironment
|
||||
{
|
||||
/// <summary>
|
||||
|
|
|
|||
|
|
@ -21,12 +21,29 @@ namespace Microsoft.AspNetCore.Routing.Internal
|
|||
private static readonly RouteValueDictionary EmptyAmbientValues = new RouteValueDictionary();
|
||||
|
||||
private readonly DecisionTreeNode<OutboundMatch> _root;
|
||||
private readonly Dictionary<string, HashSet<object>> _knownValues;
|
||||
|
||||
public LinkGenerationDecisionTree(IReadOnlyList<OutboundMatch> entries)
|
||||
{
|
||||
_root = DecisionTreeBuilder<OutboundMatch>.GenerateTree(
|
||||
entries,
|
||||
new OutboundMatchClassifier());
|
||||
|
||||
_knownValues = new Dictionary<string, HashSet<object>>(StringComparer.OrdinalIgnoreCase);
|
||||
for (var i = 0; i < entries.Count; i++)
|
||||
{
|
||||
var entry = entries[i];
|
||||
foreach (var kvp in entry.Entry.RequiredLinkValues)
|
||||
{
|
||||
if (!_knownValues.TryGetValue(kvp.Key, out var values))
|
||||
{
|
||||
values = new HashSet<object>(RouteValueEqualityComparer.Default);
|
||||
_knownValues.Add(kvp.Key, values);
|
||||
}
|
||||
|
||||
values.Add(kvp.Value ?? string.Empty);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public IList<OutboundMatchResult> GetMatches(RouteValueDictionary values, RouteValueDictionary ambientValues)
|
||||
|
|
@ -93,6 +110,19 @@ namespace Microsoft.AspNetCore.Routing.Internal
|
|||
{
|
||||
Walk(results, values, ambientValues, branch, isFallbackPath);
|
||||
}
|
||||
else
|
||||
{
|
||||
// If an explicitly specified value doesn't match any branch, then speculatively walk the
|
||||
// "null" path if the value doesn't match any known value.
|
||||
//
|
||||
// This can happen when linking from a page <-> action. We want to be
|
||||
// able to use "page" and "action" as normal route parameters.
|
||||
var knownValues = _knownValues[key];
|
||||
if (!knownValues.Contains(value ?? string.Empty) && criterion.Branches.TryGetValue(string.Empty, out branch))
|
||||
{
|
||||
Walk(results, values, ambientValues, branch, isFallbackPath: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
|
|
@ -210,4 +240,4 @@ namespace Microsoft.AspNetCore.Routing.Internal
|
|||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -340,6 +340,385 @@ namespace Microsoft.AspNetCore.Routing.Internal.Routing
|
|||
Assert.Equal(entries, matches);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetMatches_ControllersWithArea_AllValuesExplicit()
|
||||
{
|
||||
// Arrange
|
||||
var entries = new List<OutboundMatch>();
|
||||
|
||||
var entry1 = CreateMatch(new { controller = "Store", action = "Buy", area = (string)null, });
|
||||
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
|
||||
entries.Add(entry1);
|
||||
|
||||
var entry2 = CreateMatch(new { controller = "Store", action = "Buy", area = "Admin" });
|
||||
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
|
||||
entries.Add(entry2);
|
||||
|
||||
var tree = new LinkGenerationDecisionTree(entries);
|
||||
|
||||
var context = CreateContext(new { controller = "Store", action = "Buy", area = "Admin" });
|
||||
|
||||
// Act
|
||||
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
|
||||
|
||||
// Assert
|
||||
// Assert
|
||||
Assert.Collection(
|
||||
matches,
|
||||
m => { Assert.Same(entry2, m); });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetMatches_ControllersWithArea_SomeValuesAmbient()
|
||||
{
|
||||
// Arrange
|
||||
var entries = new List<OutboundMatch>();
|
||||
|
||||
var entry1 = CreateMatch(new { controller = "Store", action = "Buy", area = (string)null, });
|
||||
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
|
||||
entries.Add(entry1);
|
||||
|
||||
var entry2 = CreateMatch(new { controller = "Store", action = "Buy", area = "Admin" });
|
||||
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
|
||||
entries.Add(entry2);
|
||||
|
||||
var tree = new LinkGenerationDecisionTree(entries);
|
||||
|
||||
var context = CreateContext(new { controller = "Store", }, new { action = "Buy", area = "Admin", });
|
||||
|
||||
// Act
|
||||
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
|
||||
|
||||
// Assert
|
||||
Assert.Collection(
|
||||
matches,
|
||||
m => { Assert.Same(entry2, m); },
|
||||
m => { Assert.Same(entry1, m); });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetMatches_ControllersWithArea_AllValuesAmbient()
|
||||
{
|
||||
// Arrange
|
||||
var entries = new List<OutboundMatch>();
|
||||
|
||||
var entry1 = CreateMatch(new { controller = "Store", action = "Buy", area = (string)null, });
|
||||
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
|
||||
entries.Add(entry1);
|
||||
|
||||
var entry2 = CreateMatch(new { controller = "Store", action = "Buy", area = "Admin" });
|
||||
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
|
||||
entries.Add(entry2);
|
||||
|
||||
var tree = new LinkGenerationDecisionTree(entries);
|
||||
|
||||
var context = CreateContext(new { }, new { controller = "Store", action = "Buy", area = "Admin", });
|
||||
|
||||
// Act
|
||||
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
|
||||
|
||||
// Assert
|
||||
Assert.Collection(
|
||||
matches,
|
||||
m => { Assert.Same(entry2, m); },
|
||||
m => { Assert.Same(entry1, m); });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetMatches_PagesWithArea_AllValuesExplicit()
|
||||
{
|
||||
// Arrange
|
||||
var entries = new List<OutboundMatch>();
|
||||
|
||||
var entry1 = CreateMatch(new { page = "/Store/Buy", area = (string)null, });
|
||||
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
|
||||
entries.Add(entry1);
|
||||
|
||||
var entry2 = CreateMatch(new { page = "/Store/Buy", area = "Admin" });
|
||||
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
|
||||
entries.Add(entry2);
|
||||
|
||||
var tree = new LinkGenerationDecisionTree(entries);
|
||||
|
||||
var context = CreateContext(new { page = "/Store/Buy", area = "Admin" });
|
||||
|
||||
// Act
|
||||
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
|
||||
|
||||
// Assert
|
||||
Assert.Collection(
|
||||
matches,
|
||||
m => { Assert.Same(entry2, m); });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetMatches_PagesWithArea_SomeValuesAmbient()
|
||||
{
|
||||
// Arrange
|
||||
var entries = new List<OutboundMatch>();
|
||||
|
||||
var entry1 = CreateMatch(new { page = "/Store/Buy", area = (string)null, });
|
||||
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
|
||||
entries.Add(entry1);
|
||||
|
||||
var entry2 = CreateMatch(new { page = "/Store/Buy", area = "Admin" });
|
||||
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
|
||||
entries.Add(entry2);
|
||||
|
||||
var tree = new LinkGenerationDecisionTree(entries);
|
||||
|
||||
var context = CreateContext(new { page = "/Store/Buy", }, new { area = "Admin", });
|
||||
|
||||
// Act
|
||||
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
|
||||
|
||||
// Assert
|
||||
Assert.Collection(
|
||||
matches,
|
||||
m => { Assert.Same(entry2, m); },
|
||||
m => { Assert.Same(entry1, m); });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetMatches_PagesWithArea_AllValuesAmbient()
|
||||
{
|
||||
// Arrange
|
||||
var entries = new List<OutboundMatch>();
|
||||
|
||||
var entry1 = CreateMatch(new { page = "/Store/Buy", area = (string)null, });
|
||||
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
|
||||
entries.Add(entry1);
|
||||
|
||||
var entry2 = CreateMatch(new { page = "/Store/Buy", area = "Admin" });
|
||||
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
|
||||
entries.Add(entry2);
|
||||
|
||||
var tree = new LinkGenerationDecisionTree(entries);
|
||||
|
||||
var context = CreateContext(new { }, new { page = "/Store/Buy", area = "Admin", });
|
||||
|
||||
// Act
|
||||
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
|
||||
|
||||
// Assert
|
||||
Assert.Collection(
|
||||
matches,
|
||||
m => { Assert.Same(entry2, m); },
|
||||
m => { Assert.Same(entry1, m); });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetMatches_LinkToControllerFromPage()
|
||||
{
|
||||
// Arrange
|
||||
var entries = new List<OutboundMatch>();
|
||||
|
||||
var entry1 = CreateMatch(new { controller = "Home", action = "Index", area = (string)null, page = (string)null, });
|
||||
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
|
||||
entries.Add(entry1);
|
||||
|
||||
var entry2 = CreateMatch(new { page = "/Store/Buy", area = (string)null, controller = (string)null, action = (string)null, });
|
||||
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
|
||||
entries.Add(entry2);
|
||||
|
||||
var tree = new LinkGenerationDecisionTree(entries);
|
||||
|
||||
var context = CreateContext(new { controller = "Home", action = "Index", }, new { page = "/Store/Buy", });
|
||||
|
||||
// Act
|
||||
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
|
||||
|
||||
// Assert
|
||||
Assert.Collection(
|
||||
matches,
|
||||
m => { Assert.Same(entry1, m); });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetMatches_LinkToControllerFromPage_WithArea()
|
||||
{
|
||||
// Arrange
|
||||
var entries = new List<OutboundMatch>();
|
||||
|
||||
var entry1 = CreateMatch(new { controller = "Home", action = "Index", area = "Admin", page = (string)null, });
|
||||
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
|
||||
entries.Add(entry1);
|
||||
|
||||
var entry2 = CreateMatch(new { page = "/Store/Buy", area = "Admin", controller = (string)null, action = (string)null, });
|
||||
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
|
||||
entries.Add(entry2);
|
||||
|
||||
var tree = new LinkGenerationDecisionTree(entries);
|
||||
|
||||
var context = CreateContext(new { controller = "Home", action = "Index", }, new { page = "/Store/Buy", area = "Admin", });
|
||||
|
||||
// Act
|
||||
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
|
||||
|
||||
// Assert
|
||||
Assert.Collection(
|
||||
matches,
|
||||
m => { Assert.Same(entry1, m); });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetMatches_LinkToControllerFromPage_WithPageValue()
|
||||
{
|
||||
// Arrange
|
||||
var entries = new List<OutboundMatch>();
|
||||
|
||||
var entry1 = CreateMatch(new { controller = "Home", action = "Index", area = (string)null, page = (string)null, });
|
||||
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
|
||||
entries.Add(entry1);
|
||||
|
||||
var entry2 = CreateMatch(new { page = "/Store/Buy", area = (string)null, controller = (string)null, action = (string)null, });
|
||||
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
|
||||
entries.Add(entry2);
|
||||
|
||||
var tree = new LinkGenerationDecisionTree(entries);
|
||||
|
||||
var context = CreateContext(new { controller = "Home", action = "Index", page = "16", }, new { page = "/Store/Buy", });
|
||||
|
||||
// Act
|
||||
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
|
||||
|
||||
// Assert
|
||||
Assert.Collection(
|
||||
matches,
|
||||
m => { Assert.Same(entry1, m); });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetMatches_LinkToControllerFromPage_WithPageValueAmbiguous()
|
||||
{
|
||||
// Arrange
|
||||
var entries = new List<OutboundMatch>();
|
||||
|
||||
var entry1 = CreateMatch(new { controller = "Home", action = "Index", area = (string)null, page = (string)null, });
|
||||
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
|
||||
entries.Add(entry1);
|
||||
|
||||
var entry2 = CreateMatch(new { page = "/Store/Buy", area = (string)null, controller = (string)null, action = (string)null, });
|
||||
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
|
||||
entries.Add(entry2);
|
||||
|
||||
var tree = new LinkGenerationDecisionTree(entries);
|
||||
|
||||
var context = CreateContext(new { controller = "Home", action = "Index", page = "/Store/Buy", }, new { page = "/Store/Buy", });
|
||||
|
||||
// Act
|
||||
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
|
||||
|
||||
// Assert
|
||||
Assert.Empty(matches);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetMatches_LinkToPageFromController()
|
||||
{
|
||||
// Arrange
|
||||
var entries = new List<OutboundMatch>();
|
||||
|
||||
var entry1 = CreateMatch(new { controller = "Home", action = "Index", area = (string)null, page = (string)null, });
|
||||
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
|
||||
entries.Add(entry1);
|
||||
|
||||
var entry2 = CreateMatch(new { page = "/Store/Buy", area = (string)null, controller = (string)null, action = (string)null, });
|
||||
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
|
||||
entries.Add(entry2);
|
||||
|
||||
var tree = new LinkGenerationDecisionTree(entries);
|
||||
|
||||
var context = CreateContext(new { page = "/Store/Buy", }, new { controller = "Home", action = "Index", });
|
||||
|
||||
// Act
|
||||
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
|
||||
|
||||
// Assert
|
||||
Assert.Collection(
|
||||
matches,
|
||||
m => { Assert.Same(entry2, m); });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetMatches_LinkToPageFromController_WithArea()
|
||||
{
|
||||
// Arrange
|
||||
var entries = new List<OutboundMatch>();
|
||||
|
||||
var entry1 = CreateMatch(new { controller = "Home", action = "Index", area = "Admin", page = (string)null, });
|
||||
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
|
||||
entries.Add(entry1);
|
||||
|
||||
var entry2 = CreateMatch(new { page = "/Store/Buy", area = "Admin", controller = (string)null, action = (string)null, });
|
||||
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
|
||||
entries.Add(entry2);
|
||||
|
||||
var tree = new LinkGenerationDecisionTree(entries);
|
||||
|
||||
var context = CreateContext(new { page = "/Store/Buy", }, new { controller = "Home", action = "Index", area = "Admin", });
|
||||
|
||||
// Act
|
||||
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
|
||||
|
||||
// Assert
|
||||
Assert.Collection(
|
||||
matches,
|
||||
m => { Assert.Same(entry2, m); });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetMatches_LinkToPageFromController_WithActionValue()
|
||||
{
|
||||
// Arrange
|
||||
var entries = new List<OutboundMatch>();
|
||||
|
||||
var entry1 = CreateMatch(new { controller = "Home", action = "Index", area = (string)null, page = (string)null, });
|
||||
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
|
||||
entries.Add(entry1);
|
||||
|
||||
var entry2 = CreateMatch(new { page = "/Store/Buy", area = (string)null, controller = (string)null, action = (string)null, });
|
||||
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
|
||||
entries.Add(entry2);
|
||||
|
||||
var tree = new LinkGenerationDecisionTree(entries);
|
||||
|
||||
var context = CreateContext(new { page = "/Store/Buy", action = "buy", }, new { controller = "Home", action = "Index", page = "16", });
|
||||
|
||||
// Act
|
||||
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
|
||||
|
||||
// Assert
|
||||
Assert.Collection(
|
||||
matches,
|
||||
m => { Assert.Same(entry2, m); });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetMatches_LinkToPageFromController_WithActionValueAmbiguous()
|
||||
{
|
||||
// Arrange
|
||||
var entries = new List<OutboundMatch>();
|
||||
|
||||
var entry1 = CreateMatch(new { controller = "Home", action = "Index", area = (string)null, page = (string)null, });
|
||||
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
|
||||
entries.Add(entry1);
|
||||
|
||||
var entry2 = CreateMatch(new { page = "/Store/Buy", area = (string)null, controller = (string)null, action = (string)null, });
|
||||
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
|
||||
entries.Add(entry2);
|
||||
|
||||
var tree = new LinkGenerationDecisionTree(entries);
|
||||
|
||||
var context = CreateContext(new { page = "/Store/Buy", action = "Index", }, new { controller = "Home", action = "Index", page = "16", });
|
||||
|
||||
// Act
|
||||
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
|
||||
|
||||
// Assert
|
||||
Assert.Empty(matches);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDebuggerDisplayString_GivesAFlattenedTree()
|
||||
{
|
||||
|
|
@ -392,4 +771,4 @@ namespace Microsoft.AspNetCore.Routing.Internal.Routing
|
|||
return context;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,8 @@
|
|||
using System;
|
||||
using System.Buffers;
|
||||
using System.Linq;
|
||||
using Microsoft.AspNetCore.Components.Server;
|
||||
using Microsoft.AspNetCore.Components.Services;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.ApplicationModels;
|
||||
using Microsoft.AspNetCore.Mvc.ApplicationParts;
|
||||
|
|
@ -17,8 +19,10 @@ using Microsoft.AspNetCore.Mvc.ViewFeatures;
|
|||
using Microsoft.AspNetCore.Mvc.ViewFeatures.Buffers;
|
||||
using Microsoft.AspNetCore.Mvc.ViewFeatures.Filters;
|
||||
using Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure;
|
||||
using Microsoft.AspNetCore.Mvc.ViewFeatures.RazorComponents;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.JSInterop;
|
||||
|
||||
namespace Microsoft.Extensions.DependencyInjection
|
||||
{
|
||||
|
|
@ -199,6 +203,12 @@ namespace Microsoft.Extensions.DependencyInjection
|
|||
ServiceDescriptor.Transient<IApplicationModelProvider, ViewDataAttributeApplicationModelProvider>());
|
||||
services.TryAddSingleton<SaveTempDataFilter>();
|
||||
|
||||
//
|
||||
// Component prerendering
|
||||
//
|
||||
services.TryAddSingleton<IComponentPrerenderer, MvcRazorComponentPrerenderer>();
|
||||
services.TryAddScoped<IUriHelper, HttpUriHelper>();
|
||||
services.TryAddScoped<IJSRuntime, UnsupportedJavaScriptRuntime>();
|
||||
|
||||
services.TryAddTransient<ControllerSaveTempDataPropertyFilter>();
|
||||
|
||||
|
|
|
|||
|
|
@ -1,14 +1,13 @@
|
|||
// Copyright (c) .NET Foundation. All rights reserved.
|
||||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text.Encodings.Web;
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using Microsoft.AspNetCore.Components.Rendering;
|
||||
using Microsoft.AspNetCore.Components.Server;
|
||||
using Microsoft.AspNetCore.Html;
|
||||
using Microsoft.AspNetCore.Mvc.Rendering;
|
||||
using Microsoft.AspNetCore.Mvc.ViewFeatures.RazorComponents;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
|
||||
|
|
@ -16,7 +15,7 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures
|
|||
/// <summary>
|
||||
/// Extensions for rendering components.
|
||||
/// </summary>
|
||||
public static class HtmlHelperComponentExtensions
|
||||
public static class HtmlHelperRazorComponentExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Renders the <typeparamref name="TComponent"/> <see cref="IComponent"/>.
|
||||
|
|
@ -27,7 +26,7 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures
|
|||
{
|
||||
if (htmlHelper == null)
|
||||
{
|
||||
throw new System.ArgumentNullException(nameof(htmlHelper));
|
||||
throw new ArgumentNullException(nameof(htmlHelper));
|
||||
}
|
||||
|
||||
return htmlHelper.RenderComponentAsync<TComponent>(null);
|
||||
|
|
@ -46,39 +45,21 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures
|
|||
{
|
||||
if (htmlHelper == null)
|
||||
{
|
||||
throw new System.ArgumentNullException(nameof(htmlHelper));
|
||||
throw new ArgumentNullException(nameof(htmlHelper));
|
||||
}
|
||||
|
||||
var serviceProvider = htmlHelper.ViewContext.HttpContext.RequestServices;
|
||||
var encoder = serviceProvider.GetRequiredService<HtmlEncoder>();
|
||||
var dispatcher = Renderer.CreateDefaultDispatcher();
|
||||
using (var htmlRenderer = new HtmlRenderer(serviceProvider, encoder.Encode, dispatcher))
|
||||
var httpContext = htmlHelper.ViewContext.HttpContext;
|
||||
var serviceProvider = httpContext.RequestServices;
|
||||
var prerenderer = serviceProvider.GetRequiredService<IComponentPrerenderer>();
|
||||
|
||||
var result = await prerenderer.PrerenderComponentAsync(new ComponentPrerenderingContext
|
||||
{
|
||||
var result = await dispatcher.InvokeAsync(() => htmlRenderer.RenderComponentAsync<TComponent>(
|
||||
parameters == null ?
|
||||
ParameterCollection.Empty :
|
||||
ParameterCollection.FromDictionary(HtmlHelper.ObjectToDictionary(parameters))));
|
||||
Context = httpContext,
|
||||
ComponentType = typeof(TComponent),
|
||||
Parameters = parameters == null ? ParameterCollection.Empty : ParameterCollection.FromDictionary(HtmlHelper.ObjectToDictionary(parameters))
|
||||
});
|
||||
|
||||
return new ComponentHtmlContent(result);
|
||||
}
|
||||
}
|
||||
|
||||
private class ComponentHtmlContent : IHtmlContent
|
||||
{
|
||||
private readonly IEnumerable<string> _componentResult;
|
||||
|
||||
public ComponentHtmlContent(IEnumerable<string> componentResult)
|
||||
{
|
||||
_componentResult = componentResult;
|
||||
}
|
||||
|
||||
public void WriteTo(TextWriter writer, HtmlEncoder encoder)
|
||||
{
|
||||
foreach (var element in _componentResult)
|
||||
{
|
||||
writer.Write(element);
|
||||
}
|
||||
}
|
||||
return new ComponentHtmlContent(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
// Copyright (c) .NET Foundation. All rights reserved.
|
||||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text.Encodings.Web;
|
||||
using Microsoft.AspNetCore.Html;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
|
||||
{
|
||||
internal class ComponentHtmlContent : IHtmlContent
|
||||
{
|
||||
private readonly IEnumerable<string> _componentResult;
|
||||
|
||||
public ComponentHtmlContent(IEnumerable<string> componentResult)
|
||||
{
|
||||
_componentResult = componentResult;
|
||||
}
|
||||
|
||||
public void WriteTo(TextWriter writer, HtmlEncoder encoder)
|
||||
{
|
||||
foreach (var element in _componentResult)
|
||||
{
|
||||
writer.Write(element);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,59 @@
|
|||
// Copyright (c) .NET Foundation. All rights reserved.
|
||||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using System;
|
||||
using Microsoft.AspNetCore.Components.Services;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Extensions;
|
||||
|
||||
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
|
||||
{
|
||||
internal class HttpUriHelper : UriHelperBase
|
||||
{
|
||||
private HttpContext _context;
|
||||
|
||||
public HttpUriHelper()
|
||||
{
|
||||
}
|
||||
|
||||
public void InitializeState(HttpContext context)
|
||||
{
|
||||
_context = context;
|
||||
InitializeState();
|
||||
}
|
||||
|
||||
protected override void InitializeState()
|
||||
{
|
||||
if (_context == null)
|
||||
{
|
||||
throw new InvalidOperationException($"'{typeof(HttpUriHelper)}' not initialized.");
|
||||
}
|
||||
SetAbsoluteBaseUri(GetContextBaseUri());
|
||||
SetAbsoluteUri(GetFullUri());
|
||||
}
|
||||
|
||||
private string GetFullUri()
|
||||
{
|
||||
var request = _context.Request;
|
||||
return UriHelper.BuildAbsolute(
|
||||
request.Scheme,
|
||||
request.Host,
|
||||
request.PathBase,
|
||||
request.Path,
|
||||
request.QueryString);
|
||||
}
|
||||
|
||||
private string GetContextBaseUri()
|
||||
{
|
||||
var request = _context.Request;
|
||||
return UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase);
|
||||
}
|
||||
|
||||
protected override void NavigateToCore(string uri, bool forceLoad)
|
||||
{
|
||||
// For now throw as we don't have a good way of aborting the request from here.
|
||||
throw new InvalidOperationException(
|
||||
"Redirects are not supported on a prerendering environment.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
// Copyright (c) .NET Foundation. All rights reserved.
|
||||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.JSInterop;
|
||||
|
||||
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
|
||||
{
|
||||
internal class UnsupportedJavaScriptRuntime : IJSRuntime
|
||||
{
|
||||
public Task<T> InvokeAsync<T>(string identifier, params object[] args)
|
||||
{
|
||||
throw new InvalidOperationException("JavaScript interop calls cannot be issued during server-side prerendering, because the page has not yet loaded in the browser. Prerendered components must wrap any JavaScript interop calls in conditional logic to ensure those interop calls are not attempted during prerendering.");
|
||||
}
|
||||
|
||||
public void UntrackObjectRef(DotNetObjectRef dotNetObjectRef)
|
||||
{
|
||||
throw new InvalidOperationException("JavaScript interop calls cannot be issued during server-side prerendering, because the page has not yet loaded in the browser. Prerendered components must wrap any JavaScript interop calls in conditional logic to ensure those interop calls are not attempted during prerendering.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
// Copyright (c) .NET Foundation. All rights reserved.
|
||||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Components.Rendering;
|
||||
using Microsoft.AspNetCore.Components.Server;
|
||||
using Microsoft.AspNetCore.Components.Services;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Microsoft.AspNetCore.Mvc.ViewFeatures.RazorComponents
|
||||
{
|
||||
internal class MvcRazorComponentPrerenderer : IComponentPrerenderer
|
||||
{
|
||||
private readonly HtmlEncoder _encoder;
|
||||
|
||||
public MvcRazorComponentPrerenderer(HtmlEncoder encoder)
|
||||
{
|
||||
_encoder = encoder;
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<string>> PrerenderComponentAsync(ComponentPrerenderingContext context)
|
||||
{
|
||||
var dispatcher = Renderer.CreateDefaultDispatcher();
|
||||
var parameters = context.Parameters;
|
||||
|
||||
// This shouldn't be moved to the constructor as we want a request scoped service.
|
||||
var helper = (HttpUriHelper)context.Context.RequestServices.GetRequiredService<IUriHelper>();
|
||||
helper.InitializeState(context.Context);
|
||||
using (var htmlRenderer = new HtmlRenderer(context.Context.RequestServices, _encoder.Encode, dispatcher))
|
||||
{
|
||||
return await dispatcher.InvokeAsync(() => htmlRenderer.RenderComponentAsync(
|
||||
context.ComponentType,
|
||||
parameters));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
// Copyright (c) .NET Foundation. All rights reserved.
|
||||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using System;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Microsoft.AspNetCore.Components.Server
|
||||
{
|
||||
/// <summary>
|
||||
/// The context for prerendering a component.
|
||||
/// </summary>
|
||||
public class ComponentPrerenderingContext
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the component type.
|
||||
/// </summary>
|
||||
public Type ComponentType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the parameters for the component.
|
||||
/// </summary>
|
||||
public ParameterCollection Parameters { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="HttpContext"/> in which the prerendering has been initiated.
|
||||
/// </summary>
|
||||
public HttpContext Context { get; set; }
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
// Copyright (c) .NET Foundation. All rights reserved.
|
||||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Microsoft.AspNetCore.Components.Server
|
||||
{
|
||||
/// <summary>
|
||||
/// Prerrenders <see cref="IComponent"/> instances.
|
||||
/// </summary>
|
||||
public interface IComponentPrerenderer
|
||||
{
|
||||
/// <summary>
|
||||
/// Prerrenders the component <see cref="ComponentPrerenderingContext.ComponentType"/>.
|
||||
/// </summary>
|
||||
/// <param name="context">The context in which the prerrendering is happening.</param>
|
||||
/// <returns><see cref="Task{TResult}"/> that will complete when the prerendering is done.</returns>
|
||||
Task<IEnumerable<string>> PrerenderComponentAsync(ComponentPrerenderingContext context);
|
||||
}
|
||||
}
|
||||
|
|
@ -2,15 +2,18 @@
|
|||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using Microsoft.AspNetCore.Components.RenderTree;
|
||||
using Microsoft.AspNetCore.Components.Server;
|
||||
using Microsoft.AspNetCore.Components.Services;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc.Rendering;
|
||||
using Microsoft.AspNetCore.Mvc.ViewFeatures.RazorComponents;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.JSInterop;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
|
|
@ -53,6 +56,82 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Test
|
|||
Assert.Equal("<p>Hello Steve!</p>", content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CanCatch_ComponentWithSynchronousException()
|
||||
{
|
||||
// Arrange
|
||||
var helper = CreateHelper();
|
||||
|
||||
// Act & Assert
|
||||
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => helper.RenderComponentAsync<ExceptionComponent>(new
|
||||
{
|
||||
IsAsync = false
|
||||
}));
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Threw an exception synchronously", exception.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CanCatch_ComponentWithAsynchronousException()
|
||||
{
|
||||
// Arrange
|
||||
var helper = CreateHelper();
|
||||
|
||||
// Act & Assert
|
||||
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => helper.RenderComponentAsync<ExceptionComponent>(new
|
||||
{
|
||||
IsAsync = true
|
||||
}));
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Threw an exception asynchronously", exception.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Rendering_ComponentWithJsInteropThrows()
|
||||
{
|
||||
// Arrange
|
||||
var helper = CreateHelper();
|
||||
|
||||
// Act & Assert
|
||||
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => helper.RenderComponentAsync<ExceptionComponent>(new
|
||||
{
|
||||
JsInterop = true
|
||||
}));
|
||||
|
||||
// Assert
|
||||
Assert.Equal("JavaScript interop calls cannot be issued during server-side prerendering, " +
|
||||
"because the page has not yet loaded in the browser. Prerendered components must wrap any JavaScript " +
|
||||
"interop calls in conditional logic to ensure those interop calls are not attempted during prerendering.",
|
||||
exception.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UriHelperRedirect_ThrowsInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
var ctx = new DefaultHttpContext();
|
||||
ctx.Request.Scheme = "http";
|
||||
ctx.Request.Host = new HostString("localhost");
|
||||
ctx.Request.PathBase = "/base";
|
||||
ctx.Request.Path = "/path";
|
||||
ctx.Request.QueryString = new QueryString("?query=value");
|
||||
|
||||
var helper = CreateHelper(ctx);
|
||||
var writer = new StringWriter();
|
||||
|
||||
// Act
|
||||
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => helper.RenderComponentAsync<RedirectComponent>(new
|
||||
{
|
||||
RedirectUri = "http://localhost/redirect"
|
||||
}));
|
||||
|
||||
Assert.Equal("Redirects are not supported on a prerendering environment.", exception.Message);
|
||||
}
|
||||
|
||||
|
||||
|
||||
[Fact]
|
||||
public async Task CanRender_AsyncComponent()
|
||||
{
|
||||
|
|
@ -108,23 +187,32 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Test
|
|||
var content = writer.ToString();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expectedContent.Replace("\r\n","\n"), content);
|
||||
Assert.Equal(expectedContent.Replace("\r\n", "\n"), content);
|
||||
}
|
||||
|
||||
private static IHtmlHelper CreateHelper(Action<IServiceCollection> configureServices = null)
|
||||
private static IHtmlHelper CreateHelper(HttpContext ctx = null, Action<IServiceCollection> configureServices = null)
|
||||
{
|
||||
var serviceCollection = new ServiceCollection();
|
||||
serviceCollection.AddSingleton<HtmlEncoder>(HtmlEncoder.Default);
|
||||
configureServices?.Invoke(serviceCollection);
|
||||
var services = new ServiceCollection();
|
||||
services.AddSingleton(HtmlEncoder.Default);
|
||||
services.AddSingleton<IJSRuntime,UnsupportedJavaScriptRuntime>();
|
||||
services.AddSingleton<IUriHelper,HttpUriHelper>();
|
||||
services.AddSingleton<IComponentPrerenderer, MvcRazorComponentPrerenderer>();
|
||||
|
||||
configureServices?.Invoke(services);
|
||||
|
||||
var helper = new Mock<IHtmlHelper>();
|
||||
var context = ctx ?? new DefaultHttpContext();
|
||||
context.RequestServices = services.BuildServiceProvider();
|
||||
context.Request.Scheme = "http";
|
||||
context.Request.Host = new HostString("localhost");
|
||||
context.Request.PathBase = "/base";
|
||||
context.Request.Path = "/path";
|
||||
context.Request.QueryString = QueryString.FromUriComponent("?query=value");
|
||||
|
||||
helper.Setup(h => h.ViewContext)
|
||||
.Returns(new ViewContext()
|
||||
{
|
||||
HttpContext = new DefaultHttpContext()
|
||||
{
|
||||
RequestServices = serviceCollection.BuildServiceProvider()
|
||||
}
|
||||
HttpContext = context
|
||||
});
|
||||
return helper.Object;
|
||||
}
|
||||
|
|
@ -151,6 +239,47 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Test
|
|||
}
|
||||
}
|
||||
|
||||
private class RedirectComponent : ComponentBase
|
||||
{
|
||||
[Inject] IUriHelper UriHelper { get; set; }
|
||||
|
||||
[Parameter] public string RedirectUri { get; set; }
|
||||
|
||||
[Parameter] public bool Force { get; set; }
|
||||
|
||||
protected override void OnInit()
|
||||
{
|
||||
UriHelper.NavigateTo(RedirectUri, Force);
|
||||
}
|
||||
}
|
||||
|
||||
private class ExceptionComponent : ComponentBase
|
||||
{
|
||||
[Parameter] bool IsAsync { get; set; }
|
||||
|
||||
[Parameter] bool JsInterop { get; set; }
|
||||
|
||||
[Inject] IJSRuntime JsRuntime { get; set; }
|
||||
|
||||
protected override async Task OnParametersSetAsync()
|
||||
{
|
||||
if (JsInterop)
|
||||
{
|
||||
await JsRuntime.InvokeAsync<int>("window.alert", "Interop!");
|
||||
}
|
||||
|
||||
if (!IsAsync)
|
||||
{
|
||||
throw new InvalidOperationException("Threw an exception synchronously");
|
||||
}
|
||||
else
|
||||
{
|
||||
await Task.Yield();
|
||||
throw new InvalidOperationException("Threw an exception asynchronously");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class GreetingComponent : ComponentBase
|
||||
{
|
||||
[Parameter] public string Name { get; set; }
|
||||
|
|
|
|||
|
|
@ -293,6 +293,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Mvc.Ra
|
|||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation.Test", "Mvc.Razor.RuntimeCompilation\test\Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation.Test.csproj", "{2FFB927A-C039-4A1F-83A5-CBBB664A0E81}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Components.Server", "..\Components\Server\src\Microsoft.AspNetCore.Components.Server.csproj", "{916BF32D-6896-4D02-BBD1-A72878FDBDFF}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
|
|
@ -1641,6 +1643,18 @@ Global
|
|||
{2FFB927A-C039-4A1F-83A5-CBBB664A0E81}.Release|Mixed Platforms.Build.0 = Release|Any CPU
|
||||
{2FFB927A-C039-4A1F-83A5-CBBB664A0E81}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{2FFB927A-C039-4A1F-83A5-CBBB664A0E81}.Release|x86.Build.0 = Release|Any CPU
|
||||
{916BF32D-6896-4D02-BBD1-A72878FDBDFF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{916BF32D-6896-4D02-BBD1-A72878FDBDFF}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{916BF32D-6896-4D02-BBD1-A72878FDBDFF}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
|
||||
{916BF32D-6896-4D02-BBD1-A72878FDBDFF}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
|
||||
{916BF32D-6896-4D02-BBD1-A72878FDBDFF}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{916BF32D-6896-4D02-BBD1-A72878FDBDFF}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{916BF32D-6896-4D02-BBD1-A72878FDBDFF}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{916BF32D-6896-4D02-BBD1-A72878FDBDFF}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{916BF32D-6896-4D02-BBD1-A72878FDBDFF}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
|
||||
{916BF32D-6896-4D02-BBD1-A72878FDBDFF}.Release|Mixed Platforms.Build.0 = Release|Any CPU
|
||||
{916BF32D-6896-4D02-BBD1-A72878FDBDFF}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{916BF32D-6896-4D02-BBD1-A72878FDBDFF}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
|
@ -1758,6 +1772,7 @@ Global
|
|||
{F49A6E01-BFC5-4CEB-9A2C-19DDD3539510} = {25C08DED-1C7D-4C6D-B1CC-F340C1B21DE7}
|
||||
{0CE75D4A-4EFD-434A-99CD-7776AE2BFD39} = {1261FF02-C7F8-4395-AA8A-29F69FC9870B}
|
||||
{2FFB927A-C039-4A1F-83A5-CBBB664A0E81} = {1261FF02-C7F8-4395-AA8A-29F69FC9870B}
|
||||
{916BF32D-6896-4D02-BBD1-A72878FDBDFF} = {5FE3048A-E96B-44F8-A7C4-FC590D7E04B4}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {63D344F6-F86D-40E6-85B9-0AABBE338C4A}
|
||||
|
|
|
|||
|
|
@ -481,6 +481,9 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
|
|||
var expected = new[]
|
||||
{
|
||||
"BasicWebSite",
|
||||
"Microsoft.AspNetCore.Components.Server",
|
||||
"Microsoft.AspNetCore.SpaServices",
|
||||
"Microsoft.AspNetCore.SpaServices.Extensions",
|
||||
"Microsoft.AspNetCore.Mvc.TagHelpers",
|
||||
"Microsoft.AspNetCore.Mvc.Razor",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ using System.Net;
|
|||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
using AngleSharp.Parser.Html;
|
||||
using BasicWebSite;
|
||||
using BasicWebSite.Services;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Xunit;
|
||||
|
|
@ -15,11 +16,14 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
|
|||
{
|
||||
public ComponentRenderingFunctionalTests(MvcTestFixture<BasicWebSite.StartupWithoutEndpointRouting> fixture)
|
||||
{
|
||||
Factory = fixture;
|
||||
Client = Client ?? CreateClient(fixture);
|
||||
}
|
||||
|
||||
public HttpClient Client { get; }
|
||||
|
||||
public MvcTestFixture<StartupWithoutEndpointRouting> Factory { get; }
|
||||
|
||||
[Fact]
|
||||
public async Task Renders_BasicComponent()
|
||||
{
|
||||
|
|
@ -33,6 +37,53 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
|
|||
AssertComponent("\n <p>Hello world!</p>\n", "Greetings", content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Renders_BasicComponent_UsingRazorComponents_Prerrenderer()
|
||||
{
|
||||
// Arrange & Act
|
||||
var client = Factory
|
||||
.WithWebHostBuilder(builder => builder.ConfigureServices(services => services.AddRazorComponents()))
|
||||
.CreateClient();
|
||||
|
||||
var response = await client.GetAsync("http://localhost/components");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
var content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
AssertComponent("\n <p>Hello world!</p>\n", "Greetings", content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Renders_RoutingComponent()
|
||||
{
|
||||
// Arrange & Act
|
||||
var response = await Client.GetAsync("http://localhost/components/routable");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
var content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
AssertComponent("\n Router component\n<p>Routed successfully</p>\n", "Routing", content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Renders_RoutingComponent_UsingRazorComponents_Prerrenderer()
|
||||
{
|
||||
// Arrange & Act
|
||||
var client = Factory
|
||||
.WithWebHostBuilder(builder => builder.ConfigureServices(services => services.AddRazorComponents()))
|
||||
.CreateClient();
|
||||
|
||||
var response = await client.GetAsync("http://localhost/components/routable");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
var content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
AssertComponent("\n Router component\n<p>Routed successfully</p>\n", "Routing", content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Renders_AsyncComponent()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1533,6 +1533,17 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
|
|||
Assert.Equal("Hello from middleware after routing", content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CanUseLinkGeneration_To_ConventionalActionWithPageParameter()
|
||||
{
|
||||
// Act
|
||||
var response = await Client.GetAsync("/PageParameter/LinkToPageParameter");
|
||||
|
||||
// Assert
|
||||
await response.AssertStatusCodeAsync(HttpStatusCode.OK);
|
||||
var content = await response.Content.ReadAsStringAsync();
|
||||
Assert.Equal("/PageParameter/PageParameter?page=17", content);
|
||||
}
|
||||
|
||||
protected static LinkBuilder LinkFrom(string url)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@
|
|||
<Reference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" />
|
||||
|
||||
<Reference Include="Microsoft.AspNetCore.Authentication" />
|
||||
<Reference Include="Microsoft.AspNetCore.Components.Server" />
|
||||
<Reference Include="Microsoft.AspNetCore.Localization.Routing" />
|
||||
<Reference Include="Microsoft.AspNetCore.Server.IISIntegration" />
|
||||
<Reference Include="Microsoft.AspNetCore.Server.Kestrel" />
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ using Microsoft.AspNetCore.Mvc;
|
|||
|
||||
namespace BasicWebSite.Controllers
|
||||
{
|
||||
public class ComponentsController : Controller
|
||||
public class RazorComponentsController : Controller
|
||||
{
|
||||
private static WeatherRow[] _weatherData = new[]
|
||||
{
|
||||
|
|
@ -51,6 +51,7 @@ namespace BasicWebSite.Controllers
|
|||
};
|
||||
|
||||
[HttpGet("/components")]
|
||||
[HttpGet("/components/routable")]
|
||||
public IActionResult Index()
|
||||
{
|
||||
return View();
|
||||
|
|
@ -0,0 +1 @@
|
|||
<p>Route not found</p>
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
@page "/components/routable"
|
||||
<p>Routed successfully</p>
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
Router component
|
||||
<Router
|
||||
AppAssembly="System.Reflection.Assembly.GetAssembly(typeof(RouterContainer))"
|
||||
FallbackComponent="typeof(Fallback)">
|
||||
</Router>
|
||||
|
|
@ -6,4 +6,8 @@
|
|||
|
||||
<div id="FetchData">
|
||||
@(await Html.RenderComponentAsync<FetchData>(new { StartDate = new DateTime(2019, 01, 15) }))
|
||||
</div>
|
||||
|
||||
<div id="Routing">
|
||||
@(await Html.RenderComponentAsync<RouterContainer>())
|
||||
</div>
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
// Copyright (c) .NET Foundation. All rights reserved.
|
||||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace RoutingWebSite.Controllers
|
||||
{
|
||||
public class PageParameterController : Controller
|
||||
{
|
||||
// We've had issues with using 'page' as a parameter in tandem with conventional
|
||||
// routing + razor pages.
|
||||
public ActionResult PageParameter(string page)
|
||||
{
|
||||
return Content($"page={page}");
|
||||
}
|
||||
|
||||
[HttpGet("/PageParameter/LinkToPageParameter")]
|
||||
public ActionResult LinkToPageParameter()
|
||||
{
|
||||
return Content(Url.Action(nameof(PageParameter), new { page = "17", }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -10,6 +10,7 @@
|
|||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Components.Server" Version="${MicrosoftAspNetCoreComponentsServerPackageVersion}" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="${MicrosoftAspNetCoreMvcNewtonsoftJsonPackageVersion}" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -1,12 +0,0 @@
|
|||
using Microsoft.AspNetCore.Components.Builder;
|
||||
|
||||
namespace RazorComponentsWeb_CSharp.Components
|
||||
{
|
||||
public class Startup
|
||||
{
|
||||
public void Configure(IComponentsApplicationBuilder app)
|
||||
{
|
||||
app.AddComponent<App>("app");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
@page "{*clientPath}"
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>RazorComponentsWeb-CSharp</title>
|
||||
<base href="~/" />
|
||||
<environment include="Development">
|
||||
<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />
|
||||
</environment>
|
||||
<environment exclude="Development">
|
||||
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
|
||||
asp-fallback-href="css/bootstrap/bootstrap.min.css"
|
||||
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute"
|
||||
crossorigin="anonymous"
|
||||
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"/>
|
||||
</environment>
|
||||
<link href="css/site.css" rel="stylesheet" />
|
||||
</head>
|
||||
<body>
|
||||
<app>@(await Html.RenderComponentAsync<App>())</app>
|
||||
|
||||
<script src="_framework/components.server.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
@using RazorComponentsWeb_CSharp.Components
|
||||
@namespace RazorComponentsWeb_CSharp.Pages
|
||||
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
|
||||
|
|
@ -10,6 +10,7 @@ using Microsoft.AspNetCore.HttpsPolicy;
|
|||
#endif
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using RazorComponentsWeb_CSharp.Components;
|
||||
using RazorComponentsWeb_CSharp.Services;
|
||||
|
||||
namespace RazorComponentsWeb_CSharp
|
||||
|
|
@ -20,8 +21,12 @@ namespace RazorComponentsWeb_CSharp
|
|||
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
|
||||
public void ConfigureServices(IServiceCollection services)
|
||||
{
|
||||
services.AddMvc()
|
||||
.AddNewtonsoftJson();
|
||||
|
||||
services.AddRazorComponents();
|
||||
|
||||
services.AddSingleton<WeatherForecastService>();
|
||||
services.AddRazorComponents<Components.Startup>();
|
||||
}
|
||||
|
||||
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
|
||||
|
|
@ -43,7 +48,12 @@ namespace RazorComponentsWeb_CSharp
|
|||
app.UseHttpsRedirection();
|
||||
#endif
|
||||
app.UseStaticFiles();
|
||||
app.UseRazorComponents<Components.Startup>();
|
||||
|
||||
app.UseRouting(routes =>
|
||||
{
|
||||
routes.MapRazorPages();
|
||||
routes.MapComponentHub<App>("app");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,16 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width" />
|
||||
<title>RazorComponentsWeb-CSharp</title>
|
||||
<base href="/" />
|
||||
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
|
||||
<link href="css/site.css" rel="stylesheet" />
|
||||
</head>
|
||||
<body>
|
||||
<app>Loading...</app>
|
||||
|
||||
<script src="_framework/components.server.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -17,6 +17,13 @@
|
|||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="${MicrosoftAspNetCoreMvcNewtonsoftJsonPackageVersion}" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.SpaServices.Extensions" Version="${MicrosoftAspNetCoreSpaServicesExtensionsPackageVersion}" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.ApiAuthorization.IdentityServer" Version="${MicrosoftAspNetCoreApiAuthorizationIdentityServerPackageVersion}" Condition=" '$(IndividualLocalAuth)' == 'True' " />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="${MicrosoftAspNetCoreDiagnosticsEntityFrameworkCorePackageVersion}" Condition=" '$(IndividualLocalAuth)' == 'True' " />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="${MicrosoftAspNetCoreIdentityEntityFrameworkCorePackageVersion}" Condition=" '$(IndividualLocalAuth)' == 'True' " />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="${MicrosoftAspNetCoreIdentityUIPackageVersion}" Condition=" '$(IndividualLocalAuth)' == 'True' " />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="${MicrosoftEntityFrameworkCoreSqlServerPackageVersion}" Condition=" '$(IndividualLocalAuth)' == 'True' AND '$(UseLocalDB)' == 'True'" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="${MicrosoftEntityFrameworkCoreSqlitePackageVersion}" Condition=" '$(IndividualLocalAuth)' == 'True' AND '$(UseLocalDB)' != 'True'" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="${MicrosoftEntityFrameworkCoreToolsPackageVersion}" Condition=" '$(IndividualLocalAuth)' == 'True' " />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
|
|||
|
|
@ -9,12 +9,28 @@
|
|||
<IsShippingPackage>true</IsShippingPackage>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<!-- Lists the versions of dependencies not built in this repo. Packages produced from this repo should be listed as a PackageVersionVariableReference. -->
|
||||
<GeneratedContentProperties>
|
||||
MicrosoftEntityFrameworkCoreSqlitePackageVersion=$(MicrosoftEntityFrameworkCoreSqlitePackageVersion);
|
||||
MicrosoftEntityFrameworkCoreSqlServerPackageVersion=$(MicrosoftEntityFrameworkCoreSqlServerPackageVersion);
|
||||
MicrosoftEntityFrameworkCoreToolsPackageVersion=$(MicrosoftEntityFrameworkCoreToolsPackageVersion);
|
||||
MicrosoftExtensionsHostingPackageVersion=$(MicrosoftExtensionsHostingPackageVersion);
|
||||
MicrosoftNETCoreAppPackageVersion=$(MicrosoftNETCoreAppPackageVersion);
|
||||
</GeneratedContentProperties>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- These projects product packages that the templates depend on. See GenerateContent.targets -->
|
||||
<PackageVersionVariableReference Include="$(RepositoryRoot)src\Mvc\Mvc.NewtonsoftJson\src\Microsoft.AspNetCore.Mvc.NewtonsoftJson.csproj" />
|
||||
<PackageVersionVariableReference Include="$(RepositoryRoot)src\Middleware\SpaServices.Extensions\src\Microsoft.AspNetCore.SpaServices.Extensions.csproj" />
|
||||
<PackageVersionVariableReference Include="$(RepositoryRoot)src\Identity\ApiAuthorization.IdentityServer\src\Microsoft.AspNetCore.ApiAuthorization.IdentityServer.csproj" />
|
||||
<PackageVersionVariableReference Include="$(RepositoryRoot)src\Identity\EntityFrameworkCore\src\Microsoft.AspNetCore.Identity.EntityFrameworkCore.csproj" />
|
||||
<PackageVersionVariableReference Include="$(RepositoryRoot)src\Identity\UI\src\Microsoft.AspNetCore.Identity.UI.csproj" />
|
||||
<PackageVersionVariableReference Include="$(RepositoryRoot)src\Middleware\Diagnostics.EntityFrameworkCore\src\Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
<ItemGroup>
|
||||
<GeneratedContent Include="Angular-CSharp.csproj.in" OutputPath="content/Angular-CSharp/Company.WebApplication1.csproj" />
|
||||
<GeneratedContent Include="React-CSharp.csproj.in" OutputPath="content/React-CSharp/Company.WebApplication1.csproj" />
|
||||
|
|
|
|||
|
|
@ -14,6 +14,13 @@
|
|||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="${MicrosoftAspNetCoreMvcNewtonsoftJsonPackageVersion}" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.SpaServices.Extensions" Version="${MicrosoftAspNetCoreSpaServicesExtensionsPackageVersion}" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.ApiAuthorization.IdentityServer" Version="${MicrosoftAspNetCoreApiAuthorizationIdentityServerPackageVersion}" Condition=" '$(IndividualLocalAuth)' == 'True' " />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="${MicrosoftAspNetCoreDiagnosticsEntityFrameworkCorePackageVersion}" Condition=" '$(IndividualLocalAuth)' == 'True' " />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="${MicrosoftAspNetCoreIdentityEntityFrameworkCorePackageVersion}" Condition=" '$(IndividualLocalAuth)' == 'True' " />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="${MicrosoftAspNetCoreIdentityUIPackageVersion}" Condition=" '$(IndividualLocalAuth)' == 'True' " />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="${MicrosoftEntityFrameworkCoreSqlServerPackageVersion}" Condition=" '$(IndividualLocalAuth)' == 'True' AND '$(UseLocalDB)' == 'True'" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="${MicrosoftEntityFrameworkCoreSqlitePackageVersion}" Condition=" '$(IndividualLocalAuth)' == 'True' AND '$(UseLocalDB)' != 'True'" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="${MicrosoftEntityFrameworkCoreToolsPackageVersion}" Condition=" '$(IndividualLocalAuth)' == 'True' " />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
|
|||
|
|
@ -1,13 +1,12 @@
|
|||
{
|
||||
"$schema": "http://json.schemastore.org/dotnetcli.host",
|
||||
"symbolInfo": {
|
||||
"UseLocalDB": {
|
||||
"longName": "use-local-db"
|
||||
},
|
||||
"Framework": {
|
||||
"longName": "framework"
|
||||
},
|
||||
"skipRestore": {
|
||||
"longName": "no-restore",
|
||||
"shortName": ""
|
||||
},
|
||||
"HttpPort": {
|
||||
"isHidden": true
|
||||
},
|
||||
|
|
@ -18,9 +17,19 @@
|
|||
"longName": "exclude-launch-settings",
|
||||
"shortName": ""
|
||||
},
|
||||
"UserSecretsId": {
|
||||
"isHidden": true
|
||||
},
|
||||
"skipRestore": {
|
||||
"longName": "no-restore",
|
||||
"shortName": ""
|
||||
},
|
||||
"NoHttps": {
|
||||
"longName": "no-https",
|
||||
"shortName": ""
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"usageExamples": [
|
||||
"--auth Individual"
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,22 +23,88 @@
|
|||
"exclude": [
|
||||
".template.config/**"
|
||||
],
|
||||
"copyOnly": [
|
||||
"wwwroot/**"
|
||||
],
|
||||
"modifiers": [
|
||||
{
|
||||
"condition": "(!IndividualLocalAuth)",
|
||||
"exclude": [
|
||||
"Pages/Shared/_LoginPartial.cshtml",
|
||||
"Data/**",
|
||||
"Models/**",
|
||||
"ClientApp/src/api-authorization/**",
|
||||
"Controllers/OidcConfigurationController.cs"
|
||||
]
|
||||
},
|
||||
{
|
||||
"condition": "(!IndividualLocalAuth || UseLocalDB)",
|
||||
"exclude": [
|
||||
"app.db"
|
||||
]
|
||||
},
|
||||
{
|
||||
"condition": "(ExcludeLaunchSettings)",
|
||||
"exclude": [
|
||||
"Properties/launchSettings.json"
|
||||
]
|
||||
},
|
||||
{
|
||||
"condition": "(IndividualLocalAuth && UseLocalDB)",
|
||||
"rename": {
|
||||
"Data/SQLServer/": "Data/Migrations/"
|
||||
},
|
||||
"exclude": [
|
||||
"Data/SQLite/**"
|
||||
]
|
||||
},
|
||||
{
|
||||
"condition": "(IndividualLocalAuth && !UseLocalDB)",
|
||||
"rename": {
|
||||
"Data/SQLite/": "Data/Migrations/"
|
||||
},
|
||||
"exclude": [
|
||||
"Data/SQLServer/**"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"symbols": {
|
||||
"auth": {
|
||||
"type": "parameter",
|
||||
"datatype": "choice",
|
||||
"choices": [
|
||||
{
|
||||
"choice": "None",
|
||||
"description": "No authentication"
|
||||
},
|
||||
{
|
||||
"choice": "Individual",
|
||||
"description": "Individual authentication"
|
||||
}
|
||||
],
|
||||
"defaultValue": "None",
|
||||
"description": "The type of authentication to use"
|
||||
},
|
||||
"UserSecretsId": {
|
||||
"type": "parameter",
|
||||
"datatype": "string",
|
||||
"replaces": "aspnet-Company.WebApplication1-53bc9b9d-9d6a-45d4-8429-2a2761773502",
|
||||
"defaultValue": "aspnet-Company.WebApplication1-53bc9b9d-9d6a-45d4-8429-2a2761773502",
|
||||
"description": "The ID to use for secrets (use with OrgReadAccess or Individual auth)."
|
||||
},
|
||||
"ExcludeLaunchSettings": {
|
||||
"type": "parameter",
|
||||
"datatype": "bool",
|
||||
"defaultValue": "false",
|
||||
"description": "Whether to exclude launchSettings.json from the generated template."
|
||||
"description": "Whether to exclude launchSettings.json in the generated template."
|
||||
},
|
||||
"skipRestore": {
|
||||
"type": "parameter",
|
||||
"datatype": "bool",
|
||||
"description": "If specified, skips the automatic restore of the project on create.",
|
||||
"defaultValue": "false"
|
||||
},
|
||||
"HttpPort": {
|
||||
"type": "parameter",
|
||||
|
|
@ -61,7 +127,7 @@
|
|||
"HttpsPort": {
|
||||
"type": "parameter",
|
||||
"datatype": "integer",
|
||||
"description": "Port number to use for the HTTPS endpoint in launchSettings.json. This option is only applicable when the parameter no-https is not used (no-https will be ignored if either IndividualAuth or OrganizationalAuth is used)."
|
||||
"description": "Port number to use for the HTTPS endpoint in launchSettings.json. This option is only applicable when the parameter no-https is not used (no-https will be ignored if IndividualLocalAuth is used)."
|
||||
},
|
||||
"HttpsPortGenerated": {
|
||||
"type": "generated",
|
||||
|
|
@ -80,6 +146,30 @@
|
|||
},
|
||||
"replaces": "44300"
|
||||
},
|
||||
"IndividualLocalAuth": {
|
||||
"type": "computed",
|
||||
"value": "(auth == \"Individual\")"
|
||||
},
|
||||
"NoAuth": {
|
||||
"type": "computed",
|
||||
"value": "(!(IndividualLocalAuth))"
|
||||
},
|
||||
"RequiresHttps": {
|
||||
"type": "computed",
|
||||
"value": "(IndividualLocalAuth || !NoHttps)"
|
||||
},
|
||||
"NoHttps": {
|
||||
"type": "parameter",
|
||||
"datatype": "bool",
|
||||
"defaultValue": "false",
|
||||
"description": "Whether to turn off HTTPS. This option only applies if Individual, IndividualB2C, SingleOrg, or MultiOrg aren't used for --auth."
|
||||
},
|
||||
"UseLocalDB": {
|
||||
"type": "parameter",
|
||||
"datatype": "bool",
|
||||
"defaultValue": "false",
|
||||
"description": "Whether to use LocalDB instead of SQLite. This option only applies if --auth Individual or --auth IndividualB2C is specified."
|
||||
},
|
||||
"Framework": {
|
||||
"type": "parameter",
|
||||
"description": "The target framework for the project.",
|
||||
|
|
@ -96,18 +186,6 @@
|
|||
"HostIdentifier": {
|
||||
"type": "bind",
|
||||
"binding": "HostIdentifier"
|
||||
},
|
||||
"skipRestore": {
|
||||
"type": "parameter",
|
||||
"datatype": "bool",
|
||||
"description": "If specified, skips the automatic restore of the project on create.",
|
||||
"defaultValue": "false"
|
||||
},
|
||||
"NoHttps": {
|
||||
"type": "parameter",
|
||||
"datatype": "bool",
|
||||
"defaultValue": "false",
|
||||
"description": "Whether to turn off HTTPS. This option only applies if Individual, IndividualB2C, SingleOrg, or MultiOrg aren't used for --auth."
|
||||
}
|
||||
},
|
||||
"tags": {
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -12,42 +12,43 @@
|
|||
},
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@angular/animations": "6.1.10",
|
||||
"@angular/common": "6.1.10",
|
||||
"@angular/compiler": "6.1.10",
|
||||
"@angular/core": "6.1.10",
|
||||
"@angular/forms": "6.1.10",
|
||||
"@angular/http": "6.1.10",
|
||||
"@angular/platform-browser": "6.1.10",
|
||||
"@angular/platform-browser-dynamic": "6.1.10",
|
||||
"@angular/platform-server": "6.1.10",
|
||||
"@angular/router": "6.1.10",
|
||||
"@nguniversal/module-map-ngfactory-loader": "6.0.0",
|
||||
"core-js": "^2.5.4",
|
||||
"rxjs": "^6.0.0",
|
||||
"zone.js": "^0.8.26",
|
||||
"@angular/animations": "7.2.5",
|
||||
"@angular/common": "7.2.5",
|
||||
"@angular/compiler": "7.2.5",
|
||||
"@angular/core": "7.2.5",
|
||||
"@angular/forms": "7.2.5",
|
||||
"@angular/http": "7.2.5",
|
||||
"@angular/platform-browser": "7.2.5",
|
||||
"@angular/platform-browser-dynamic": "7.2.5",
|
||||
"@angular/platform-server": "7.2.5",
|
||||
"@angular/router": "7.2.5",
|
||||
"@nguniversal/module-map-ngfactory-loader": "7.1.0",
|
||||
"core-js": "^2.6.5",
|
||||
"rxjs": "^6.4.0",
|
||||
"zone.js": "^0.8.29",
|
||||
"aspnet-prerendering": "^3.0.1",
|
||||
"bootstrap": "^4.1.3",
|
||||
"bootstrap": "^4.3.1",
|
||||
"jquery": "3.3.1",
|
||||
"oidc-client": "^1.6.1",
|
||||
"popper.js": "^1.14.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@angular-devkit/build-angular": "~0.6.0",
|
||||
"@angular/cli": "~6.0.0",
|
||||
"@angular/compiler-cli": "6.1.10",
|
||||
"@angular/language-service": "^6.0.0",
|
||||
"@types/jasmine": "~2.8.6",
|
||||
"@types/jasminewd2": "~2.0.3",
|
||||
"@types/node": "~8.9.4",
|
||||
"codelyzer": "~4.2.1",
|
||||
"jasmine-core": "~2.99.1",
|
||||
"@angular-devkit/build-angular": "~0.13.2",
|
||||
"@angular/cli": "~7.3.2",
|
||||
"@angular/compiler-cli": "7.2.5",
|
||||
"@angular/language-service": "^7.2.5",
|
||||
"@types/jasmine": "~3.3.9",
|
||||
"@types/jasminewd2": "~2.0.6",
|
||||
"@types/node": "~11.9.4",
|
||||
"codelyzer": "~4.5.0",
|
||||
"jasmine-core": "~3.3.0",
|
||||
"jasmine-spec-reporter": "~4.2.1",
|
||||
"karma": "^3.0.0",
|
||||
"karma": "^4.0.0",
|
||||
"karma-chrome-launcher": "~2.2.0",
|
||||
"karma-coverage-istanbul-reporter": "~1.4.2",
|
||||
"karma-jasmine": "~1.1.1",
|
||||
"karma-jasmine-html-reporter": "^0.2.2",
|
||||
"typescript": "~2.7.2"
|
||||
"karma-coverage-istanbul-reporter": "~2.0.5",
|
||||
"karma-jasmine": "~2.0.1",
|
||||
"karma-jasmine-html-reporter": "^1.4.0",
|
||||
"typescript": "~3.2.4"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"node-sass": "^4.9.3",
|
||||
|
|
|
|||
|
|
@ -0,0 +1,81 @@
|
|||
export const ApplicationName = 'Company.WebApplication1';
|
||||
|
||||
export const ReturnUrlType = 'returnUrl';
|
||||
|
||||
export const QueryParameterNames = {
|
||||
ReturnUrl: ReturnUrlType,
|
||||
Message: 'message'
|
||||
};
|
||||
|
||||
export const LogoutActions = {
|
||||
LogoutCallback: 'logout-callback',
|
||||
Logout: 'logout',
|
||||
LoggedOut: 'logged-out'
|
||||
};
|
||||
|
||||
export const LoginActions = {
|
||||
Login: 'login',
|
||||
LoginCallback: 'login-callback',
|
||||
LoginFailed: 'login-failed',
|
||||
Profile: 'profile',
|
||||
Register: 'register'
|
||||
};
|
||||
|
||||
let applicationPaths: ApplicationPathsType = {
|
||||
DefaultLoginRedirectPath: '/',
|
||||
ApiAuthorizationClientConfigurationUrl: `/_configuration/${ApplicationName}`,
|
||||
Login: `authentication/${LoginActions.Login}`,
|
||||
LoginFailed: `authentication/${LoginActions.LoginFailed}`,
|
||||
LoginCallback: `authentication/${LoginActions.LoginCallback}`,
|
||||
Register: `authentication/${LoginActions.Register}`,
|
||||
Profile: `authentication/${LoginActions.Profile}`,
|
||||
LogOut: `authentication/${LogoutActions.Logout}`,
|
||||
LoggedOut: `authentication/${LogoutActions.LoggedOut}`,
|
||||
LogOutCallback: `authentication/${LogoutActions.LogoutCallback}`,
|
||||
LoginPathComponents: [],
|
||||
LoginFailedPathComponents: [],
|
||||
LoginCallbackPathComponents: [],
|
||||
RegisterPathComponents: [],
|
||||
ProfilePathComponents: [],
|
||||
LogOutPathComponents: [],
|
||||
LoggedOutPathComponents: [],
|
||||
LogOutCallbackPathComponents: [],
|
||||
IdentityRegisterPath: '/Identity/Account/Register',
|
||||
IdentityManagePath: '/Identity/Account/Manage'
|
||||
};
|
||||
|
||||
applicationPaths = {
|
||||
...applicationPaths,
|
||||
LoginPathComponents: applicationPaths.Login.split('/'),
|
||||
LoginFailedPathComponents: applicationPaths.LoginFailed.split('/'),
|
||||
RegisterPathComponents: applicationPaths.Register.split('/'),
|
||||
ProfilePathComponents: applicationPaths.Profile.split('/'),
|
||||
LogOutPathComponents: applicationPaths.LogOut.split('/'),
|
||||
LoggedOutPathComponents: applicationPaths.LoggedOut.split('/'),
|
||||
LogOutCallbackPathComponents: applicationPaths.LogOutCallback.split('/')
|
||||
};
|
||||
|
||||
interface ApplicationPathsType {
|
||||
readonly DefaultLoginRedirectPath: string;
|
||||
readonly ApiAuthorizationClientConfigurationUrl: string;
|
||||
readonly Login: string;
|
||||
readonly LoginFailed: string;
|
||||
readonly LoginCallback: string;
|
||||
readonly Register: string;
|
||||
readonly Profile: string;
|
||||
readonly LogOut: string;
|
||||
readonly LoggedOut: string;
|
||||
readonly LogOutCallback: string;
|
||||
readonly LoginPathComponents: string [];
|
||||
readonly LoginFailedPathComponents: string [];
|
||||
readonly LoginCallbackPathComponents: string [];
|
||||
readonly RegisterPathComponents: string [];
|
||||
readonly ProfilePathComponents: string [];
|
||||
readonly LogOutPathComponents: string [];
|
||||
readonly LoggedOutPathComponents: string [];
|
||||
readonly LogOutCallbackPathComponents: string [];
|
||||
readonly IdentityRegisterPath: string;
|
||||
readonly IdentityManagePath: string;
|
||||
}
|
||||
|
||||
export const ApplicationPaths: ApplicationPathsType = applicationPaths;
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
import { ApiAuthorizationModule } from './api-authorization.module';
|
||||
|
||||
describe('ApiAuthorizationModule', () => {
|
||||
let apiAuthorizationModule: ApiAuthorizationModule;
|
||||
|
||||
beforeEach(() => {
|
||||
apiAuthorizationModule = new ApiAuthorizationModule();
|
||||
});
|
||||
|
||||
it('should create an instance', () => {
|
||||
expect(apiAuthorizationModule).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
import { NgModule } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { LoginMenuComponent } from './login-menu/login-menu.component';
|
||||
import { LoginComponent } from './login/login.component';
|
||||
import { LogoutComponent } from './logout/logout.component';
|
||||
import { RouterModule } from '@angular/router';
|
||||
import { ApplicationPaths } from './api-authorization.constants';
|
||||
import { HttpClientModule } from '@angular/common/http';
|
||||
|
||||
@NgModule({
|
||||
imports: [
|
||||
CommonModule,
|
||||
HttpClientModule,
|
||||
RouterModule.forChild(
|
||||
[
|
||||
{ path: ApplicationPaths.Register, component: LoginComponent },
|
||||
{ path: ApplicationPaths.Profile, component: LoginComponent },
|
||||
{ path: ApplicationPaths.Login, component: LoginComponent },
|
||||
{ path: ApplicationPaths.LoginFailed, component: LoginComponent },
|
||||
{ path: ApplicationPaths.LoginCallback, component: LoginComponent },
|
||||
{ path: ApplicationPaths.LogOut, component: LogoutComponent },
|
||||
{ path: ApplicationPaths.LoggedOut, component: LogoutComponent },
|
||||
{ path: ApplicationPaths.LogOutCallback, component: LogoutComponent }
|
||||
]
|
||||
)
|
||||
],
|
||||
declarations: [LoginMenuComponent, LoginComponent, LogoutComponent],
|
||||
exports: [LoginMenuComponent, LoginComponent, LogoutComponent]
|
||||
})
|
||||
export class ApiAuthorizationModule { }
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
import { TestBed, inject } from '@angular/core/testing';
|
||||
|
||||
import { AuthorizeGuard } from './authorize.guard';
|
||||
|
||||
describe('AuthorizeGuard', () => {
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [AuthorizeGuard]
|
||||
});
|
||||
});
|
||||
|
||||
it('should ...', inject([AuthorizeGuard], (guard: AuthorizeGuard) => {
|
||||
expect(guard).toBeTruthy();
|
||||
}));
|
||||
});
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
import { Injectable } from '@angular/core';
|
||||
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
|
||||
import { Observable } from 'rxjs';
|
||||
import { AuthorizeService } from './authorize.service';
|
||||
import { tap } from 'rxjs/operators';
|
||||
import { ApplicationPaths, QueryParameterNames } from './api-authorization.constants';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class AuthorizeGuard implements CanActivate {
|
||||
constructor(private authorize: AuthorizeService, private router: Router) {
|
||||
}
|
||||
canActivate(
|
||||
_next: ActivatedRouteSnapshot,
|
||||
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
|
||||
return this.authorize.isAuthenticated()
|
||||
.pipe(tap(isAuthenticated => this.handleAuthorization(isAuthenticated, state)));
|
||||
}
|
||||
|
||||
private handleAuthorization(isAuthenticated: boolean, state: RouterStateSnapshot) {
|
||||
if (!isAuthenticated) {
|
||||
this.router.navigate(ApplicationPaths.LoginPathComponents, {
|
||||
queryParams: {
|
||||
[QueryParameterNames.ReturnUrl]: state.url
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
import { TestBed, inject } from '@angular/core/testing';
|
||||
|
||||
import { AuthorizeInterceptor } from './authorize.interceptor';
|
||||
|
||||
describe('AuthorizeInterceptor', () => {
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [AuthorizeInterceptor]
|
||||
});
|
||||
});
|
||||
|
||||
it('should be created', inject([AuthorizeInterceptor], (service: AuthorizeInterceptor) => {
|
||||
expect(service).toBeTruthy();
|
||||
}));
|
||||
});
|
||||
|
|
@ -0,0 +1,54 @@
|
|||
import { Injectable } from '@angular/core';
|
||||
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { AuthorizeService } from './authorize.service';
|
||||
import { mergeMap } from 'rxjs/operators';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class AuthorizeInterceptor implements HttpInterceptor {
|
||||
constructor(private authorize: AuthorizeService) { }
|
||||
|
||||
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
|
||||
return this.authorize.getAccessToken()
|
||||
.pipe(mergeMap(token => this.processRequestWithToken(token, req, next)));
|
||||
}
|
||||
|
||||
// Checks if there is an access_token available in the authorize service
|
||||
// and adds it to the request in case it's targeted at the same origin as the
|
||||
// single page application.
|
||||
private processRequestWithToken(token: string, req: HttpRequest<any>, next: HttpHandler) {
|
||||
if (!!token && this.isSameOriginUrl(req)) {
|
||||
req = req.clone({
|
||||
setHeaders: {
|
||||
Authorization: `Bearer ${token}`
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return next.handle(req);
|
||||
}
|
||||
|
||||
private isSameOriginUrl(req: any) {
|
||||
// It's an absolute url with the same origin.
|
||||
if (req.url.startsWith(`${window.location.origin}/`)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// It's a protocol relative url with the same origin.
|
||||
// For example: //www.example.com/api/Products
|
||||
if (req.url.startsWith(`//${window.location.host}/`)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// It's a relative url like /api/Products
|
||||
if (/^\/[^\/].*/.test(req.url)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// It's an absolute or protocol relative url that
|
||||
// doesn't have the same origin.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
import { TestBed, inject } from '@angular/core/testing';
|
||||
|
||||
import { AuthorizeService } from './authorize.service';
|
||||
|
||||
describe('AuthorizeService', () => {
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [AuthorizeService]
|
||||
});
|
||||
});
|
||||
|
||||
it('should be created', inject([AuthorizeService], (service: AuthorizeService) => {
|
||||
expect(service).toBeTruthy();
|
||||
}));
|
||||
});
|
||||
|
|
@ -0,0 +1,324 @@
|
|||
import { Injectable } from '@angular/core';
|
||||
import { User, UserManager, WebStorageStateStore } from 'oidc-client';
|
||||
import { BehaviorSubject, concat, from, Observable } from 'rxjs';
|
||||
import { filter, map, mergeMap, take, tap } from 'rxjs/operators';
|
||||
import { ApplicationPaths, ApplicationName } from './api-authorization.constants';
|
||||
|
||||
export type IAuthenticationResult =
|
||||
SuccessAuthenticationResult |
|
||||
FailureAuthenticationResult |
|
||||
RedirectAuthenticationResult;
|
||||
|
||||
export interface SuccessAuthenticationResult {
|
||||
status: AuthenticationResultStatus.Success;
|
||||
state: any;
|
||||
}
|
||||
|
||||
export interface FailureAuthenticationResult {
|
||||
status: AuthenticationResultStatus.Fail;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface RedirectAuthenticationResult {
|
||||
status: AuthenticationResultStatus.Redirect;
|
||||
redirectUrl: string;
|
||||
}
|
||||
|
||||
export enum AuthenticationResultStatus {
|
||||
Success,
|
||||
Redirect,
|
||||
Fail
|
||||
}
|
||||
|
||||
export interface IUser {
|
||||
name: string;
|
||||
}
|
||||
|
||||
// Private interfaces
|
||||
enum LoginMode {
|
||||
Silent,
|
||||
PopUp,
|
||||
Redirect
|
||||
}
|
||||
|
||||
interface IAuthenticationState {
|
||||
mode: LoginMode;
|
||||
userState?: any;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class AuthorizeService {
|
||||
private userManager: UserManager;
|
||||
private userSubject: BehaviorSubject<IUser | null> = new BehaviorSubject(null);
|
||||
|
||||
public isAuthenticated(): Observable<boolean> {
|
||||
return this.getUser().pipe(map(u => !!u));
|
||||
}
|
||||
|
||||
public getUser(): Observable<IUser | null> {
|
||||
return concat(
|
||||
this.userSubject.pipe(take(1), filter(u => !!u)),
|
||||
this.getUserFromStorage().pipe(filter(u => !!u), tap(u => this.userSubject.next(u))),
|
||||
this.userSubject.asObservable());
|
||||
}
|
||||
|
||||
public getAccessToken(): Observable<string> {
|
||||
return from(this.ensureUserManagerInitialized())
|
||||
.pipe(mergeMap(() => from(this.userManager.getUser())),
|
||||
map(user => user && user.access_token));
|
||||
}
|
||||
|
||||
// We try to authenticate the user in three different ways:
|
||||
// 1) We try to see if we can authenticate the user silently. This happens
|
||||
// when the user is already logged in on the IdP and is done using a hidden iframe
|
||||
// on the client.
|
||||
// 2) We try to authenticate the user using a PopUp Window. This might fail if there is a
|
||||
// Pop-Up blocker or the user has disabled PopUps.
|
||||
// 3) If the two methods above fail, we redirect the browser to the IdP to perform a traditional
|
||||
// redirect flow.
|
||||
public async signIn(state: any): Promise<IAuthenticationResult> {
|
||||
await this.ensureUserManagerInitialized();
|
||||
let user: User = null;
|
||||
try {
|
||||
user = await this.userManager.signinSilent(this.createArguments(LoginMode.Silent));
|
||||
this.userSubject.next(user.profile);
|
||||
return this.success(state);
|
||||
} catch (silentError) {
|
||||
// User might not be authenticated, fallback to popup authentication
|
||||
console.log('Silent authentication error: ', silentError);
|
||||
|
||||
try {
|
||||
user = await this.userManager.signinPopup(this.createArguments(LoginMode.PopUp));
|
||||
this.userSubject.next(user.profile);
|
||||
return this.success(state);
|
||||
} catch (popupError) {
|
||||
if (popupError.message === 'Popup window closed') {
|
||||
// The user explicitly cancelled the login action by closing an opened popup.
|
||||
return this.error('The user closed the window.');
|
||||
}
|
||||
console.log('Popup authentication error: ', popupError);
|
||||
|
||||
// PopUps might be blocked by the user, fallback to redirect
|
||||
try {
|
||||
const signInRequest = await this.userManager.createSigninRequest(
|
||||
this.createArguments(LoginMode.Redirect, state));
|
||||
return this.redirect(signInRequest.url);
|
||||
} catch (redirectError) {
|
||||
console.log('Redirect authentication error: ', redirectError);
|
||||
return this.error(redirectError);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// We are receiving a callback from the IdP. This code can be running in 3 situations:
|
||||
// 1) As a hidden iframe started by a silent login on signIn (above). The code in the main
|
||||
// browser window will close the iframe after returning from signInSilent.
|
||||
// 2) As a PopUp window started by a pop-up login on signIn (above). The code in the main
|
||||
// browser window will close the pop-up window after returning from signInPopUp
|
||||
// 3) On the main browser window when the IdP redirects back to the app. We will process
|
||||
// the response and redirect to the return url or display an error message.
|
||||
public async completeSignIn(url: string): Promise<IAuthenticationResult> {
|
||||
await this.ensureUserManagerInitialized();
|
||||
let response;
|
||||
try {
|
||||
response = await this.getSignInResponse(url);
|
||||
if (!!response.error) {
|
||||
return this.error(`${response.error}: ${response.error_description}`);
|
||||
}
|
||||
} catch (processSignInResponseError) {
|
||||
if (processSignInResponseError.error === 'login_required') {
|
||||
// This error is thrown by the underlying oidc client when it tries to log in
|
||||
// the user silently as in case 1 defined above and the IdP requires the user
|
||||
// to enter credentials. We let the user manager handle the response to notify
|
||||
// the main window.
|
||||
response = processSignInResponseError;
|
||||
} else {
|
||||
console.log('There was an error processing the sign-in response: ', processSignInResponseError);
|
||||
return this.error('There was an error processing the sign-in response.');
|
||||
}
|
||||
}
|
||||
|
||||
const authenticationState = response.state as IAuthenticationState;
|
||||
const mode = authenticationState.mode;
|
||||
|
||||
switch (mode) {
|
||||
case LoginMode.Silent:
|
||||
try {
|
||||
await this.userManager.signinSilentCallback(url);
|
||||
return this.success(undefined);
|
||||
} catch (silentCallbackError) {
|
||||
console.log('Silent callback authentication error: ', silentCallbackError);
|
||||
return this.error('Silent callback authentication error');
|
||||
}
|
||||
case LoginMode.PopUp:
|
||||
try {
|
||||
await this.userManager.signinPopupCallback(url);
|
||||
return this.success(undefined);
|
||||
} catch (popupCallbackError) {
|
||||
console.log('Popup callback authentication error: ', popupCallbackError);
|
||||
return this.error('Popup callback authentication error.');
|
||||
}
|
||||
case LoginMode.Redirect:
|
||||
try {
|
||||
const user = await this.userManager.signinRedirectCallback(url);
|
||||
this.userSubject.next(user.profile);
|
||||
return this.success(response.state.userState);
|
||||
} catch (redirectCallbackError) {
|
||||
console.log('Redirect callback authentication error: ', redirectCallbackError);
|
||||
return this.error('Redirect callback authentication error.');
|
||||
}
|
||||
default:
|
||||
throw new Error(`Invalid login mode '${mode}'.`);
|
||||
}
|
||||
}
|
||||
// We try to sign out the user in two different ways:
|
||||
// 1) We try to do a sign-out using a PopUp Window. This might fail if there is a
|
||||
// Pop-Up blocker or the user has disabled PopUps.
|
||||
// 2) If the method above fails, we redirect the browser to the IdP to perform a traditional
|
||||
// post logout redirect flow.
|
||||
public async signOut(state: any): Promise<IAuthenticationResult> {
|
||||
await this.ensureUserManagerInitialized();
|
||||
try {
|
||||
await this.userManager.signoutPopup(this.createArguments(LoginMode.PopUp));
|
||||
this.userSubject.next(null);
|
||||
return this.success(state);
|
||||
} catch (popupSignOutError) {
|
||||
console.log('Popup signout error: ', popupSignOutError);
|
||||
try {
|
||||
const signInRequest = await this.userManager.createSignoutRequest(
|
||||
this.createArguments(LoginMode.Redirect, state));
|
||||
return this.redirect(signInRequest.url);
|
||||
} catch (redirectSignOutError) {
|
||||
console.log('Redirect signout error: ', popupSignOutError);
|
||||
return this.error(redirectSignOutError);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// We are receiving a callback from the IdP. This code can be running in 2 situations:
|
||||
// 1) As a PopUp window started by a pop-up login on signOut (above). The code in the main
|
||||
// browser window will close the pop-up window after returning from signOutPopUp
|
||||
// 2) On the main browser window when the IdP redirects back to the app. We will process
|
||||
// the response and redirect to the logged-out url or display an error message.
|
||||
public async completeSignOut(url: string): Promise<IAuthenticationResult> {
|
||||
await this.ensureUserManagerInitialized();
|
||||
let response;
|
||||
try {
|
||||
response = await await this.getSignOutResponse(url);
|
||||
} catch (processSignOutResponseError) {
|
||||
console.log('There was an error processing the sign-out response: ', processSignOutResponseError);
|
||||
response = processSignOutResponseError;
|
||||
}
|
||||
|
||||
if (!!response.error) {
|
||||
return this.error(`${response.error}: ${response.error_description}`);
|
||||
}
|
||||
|
||||
const authenticationState = response.state as IAuthenticationState;
|
||||
const mode = (authenticationState && authenticationState.mode) ||
|
||||
!!window.opener ? LoginMode.PopUp : LoginMode.Redirect;
|
||||
|
||||
switch (mode) {
|
||||
case LoginMode.PopUp:
|
||||
try {
|
||||
await this.userManager.signoutPopupCallback(url);
|
||||
return this.success(response.state && response.state.userState);
|
||||
} catch (popupCallbackError) {
|
||||
console.log('Popup signout callback error: ', popupCallbackError);
|
||||
return this.error('Popup signout callback error');
|
||||
}
|
||||
case LoginMode.Redirect:
|
||||
try {
|
||||
await this.userManager.signoutRedirectCallback(url);
|
||||
this.userSubject.next(null);
|
||||
return this.success(response.state.userState);
|
||||
} catch (redirectCallbackError) {
|
||||
console.log('Redirect signout callback error: ', redirectCallbackError);
|
||||
return this.error('Redirect signout callback error');
|
||||
}
|
||||
default:
|
||||
throw new Error(`Invalid LoginMode '${mode}'.`);
|
||||
}
|
||||
}
|
||||
|
||||
private async getSignInResponse(url: string) {
|
||||
const keys = await this.userManager.settings.stateStore.getAllKeys();
|
||||
const states = keys.map(key => ({ key, state: this.userManager.settings.stateStore.get(key) }));
|
||||
for (const state of states) {
|
||||
state.state = await state.state;
|
||||
}
|
||||
try {
|
||||
const response = await this.userManager.processSigninResponse(url);
|
||||
return response;
|
||||
} finally {
|
||||
for (const state of states) {
|
||||
await this.userManager.settings.stateStore.set(state.key, state.state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async getSignOutResponse(url: string) {
|
||||
const keys = await this.userManager.settings.stateStore.getAllKeys();
|
||||
const states = keys.map(key => ({ key, state: this.userManager.settings.stateStore.get(key) }));
|
||||
for (const state of states) {
|
||||
state.state = await state.state;
|
||||
}
|
||||
try {
|
||||
const response = await this.userManager.processSignoutResponse(url);
|
||||
return response;
|
||||
} finally {
|
||||
for (const state of states) {
|
||||
await this.userManager.settings.stateStore.set(state.key, state.state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private createArguments(mode: LoginMode, state?: any): any {
|
||||
if (mode !== LoginMode.Silent) {
|
||||
return { data: { mode, userState: state } };
|
||||
} else {
|
||||
return { data: { mode, userState: state }, redirect_uri: this.userManager.settings.redirect_uri };
|
||||
}
|
||||
}
|
||||
|
||||
private error(message: string): IAuthenticationResult {
|
||||
return { status: AuthenticationResultStatus.Fail, message };
|
||||
}
|
||||
|
||||
private success(state: any): IAuthenticationResult {
|
||||
return { status: AuthenticationResultStatus.Success, state };
|
||||
}
|
||||
|
||||
private redirect(redirectUrl: string): IAuthenticationResult {
|
||||
return { status: AuthenticationResultStatus.Redirect, redirectUrl };
|
||||
}
|
||||
|
||||
private async ensureUserManagerInitialized(): Promise<void> {
|
||||
if (this.userManager !== undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const response = await fetch(ApplicationPaths.ApiAuthorizationClientConfigurationUrl);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Could not load settings for '${ApplicationName}'`);
|
||||
}
|
||||
|
||||
const settings: any = await response.json();
|
||||
settings.automaticSilentRenew = true;
|
||||
settings.includeIdTokenInSilentRenew = true;
|
||||
settings.userStore = new WebStorageStateStore({
|
||||
prefix: ApplicationName
|
||||
});
|
||||
this.userManager = new UserManager(settings);
|
||||
}
|
||||
|
||||
private getUserFromStorage(): Observable<IUser> {
|
||||
return from(this.ensureUserManagerInitialized())
|
||||
.pipe(
|
||||
mergeMap(() => this.userManager.getUser()),
|
||||
map(u => u && u.profile));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
<ul class="navbar-nav" *ngIf="isAuthenticated | async">
|
||||
<li class="nav-item">
|
||||
<a class="nav-link text-dark" [routerLink]='["/authentication/profile"]' title="Manage">Hello {{ userName | async }}</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link text-dark" [routerLink]='["/authentication/logout"]' [state]='{ local: true }' title="Logout">Logout</a>
|
||||
</li>
|
||||
</ul>
|
||||
<ul class="navbar-nav" *ngIf="!(isAuthenticated | async)">
|
||||
<li class="nav-item">
|
||||
<a class="nav-link text-dark" [routerLink]='["/authentication/register"]'>Register</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link text-dark" [routerLink]='["/authentication/login"]'>Login</a>
|
||||
</li>
|
||||
</ul>
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
|
||||
import { LoginMenuComponent } from './login-menu.component';
|
||||
|
||||
describe('LoginMenuComponent', () => {
|
||||
let component: LoginMenuComponent;
|
||||
let fixture: ComponentFixture<LoginMenuComponent>;
|
||||
|
||||
beforeEach(async(() => {
|
||||
TestBed.configureTestingModule({
|
||||
declarations: [ LoginMenuComponent ]
|
||||
})
|
||||
.compileComponents();
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = TestBed.createComponent(LoginMenuComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
import { Component, OnInit } from '@angular/core';
|
||||
import { AuthorizeService } from '../authorize.service';
|
||||
import { Observable } from 'rxjs';
|
||||
import { map, tap } from 'rxjs/operators';
|
||||
|
||||
@Component({
|
||||
selector: 'app-login-menu',
|
||||
templateUrl: './login-menu.component.html',
|
||||
styleUrls: ['./login-menu.component.css']
|
||||
})
|
||||
export class LoginMenuComponent implements OnInit {
|
||||
public isAuthenticated: Observable<boolean>;
|
||||
public userName: Observable<string>;
|
||||
|
||||
constructor(private authorizeService: AuthorizeService) { }
|
||||
|
||||
ngOnInit() {
|
||||
this.isAuthenticated = this.authorizeService.isAuthenticated();
|
||||
this.userName = this.authorizeService.getUser().pipe(map(u => u && u.name));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
<p>{{ message | async }}</p>
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
|
||||
import { LoginComponent } from './login.component';
|
||||
|
||||
describe('LoginComponent', () => {
|
||||
let component: LoginComponent;
|
||||
let fixture: ComponentFixture<LoginComponent>;
|
||||
|
||||
beforeEach(async(() => {
|
||||
TestBed.configureTestingModule({
|
||||
declarations: [ LoginComponent ]
|
||||
})
|
||||
.compileComponents();
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = TestBed.createComponent(LoginComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,132 @@
|
|||
import { Component, OnInit } from '@angular/core';
|
||||
import { AuthorizeService, AuthenticationResultStatus } from '../authorize.service';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { BehaviorSubject } from 'rxjs';
|
||||
import { LoginActions, QueryParameterNames, ApplicationPaths, ReturnUrlType } from '../api-authorization.constants';
|
||||
|
||||
// The main responsibility of this component is to handle the user's login process.
|
||||
// This is the starting point for the login process. Any component that needs to authenticate
|
||||
// a user can simply perform a redirect to this component with a returnUrl query parameter and
|
||||
// let the component perform the login and return back to the return url.
|
||||
@Component({
|
||||
selector: 'app-login',
|
||||
templateUrl: './login.component.html',
|
||||
styleUrls: ['./login.component.css']
|
||||
})
|
||||
export class LoginComponent implements OnInit {
|
||||
private message = new BehaviorSubject<string>(null);
|
||||
|
||||
constructor(
|
||||
private authorizeService: AuthorizeService,
|
||||
private activatedRoute: ActivatedRoute,
|
||||
private router: Router) { }
|
||||
|
||||
async ngOnInit() {
|
||||
const action = this.activatedRoute.snapshot.url[1];
|
||||
switch (action.path) {
|
||||
case LoginActions.Login:
|
||||
await this.login(this.getReturnUrl());
|
||||
break;
|
||||
case LoginActions.LoginCallback:
|
||||
await this.processLoginCallback();
|
||||
break;
|
||||
case LoginActions.LoginFailed:
|
||||
const message = this.activatedRoute.snapshot.queryParamMap.get(QueryParameterNames.Message);
|
||||
this.message.next(message);
|
||||
break;
|
||||
case LoginActions.Profile:
|
||||
this.redirectToProfile();
|
||||
break;
|
||||
case LoginActions.Register:
|
||||
this.redirectToRegister();
|
||||
break;
|
||||
default:
|
||||
throw new Error(`Invalid action '${action}'`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private async login(returnUrl: string): Promise<void> {
|
||||
const state: INavigationState = { returnUrl };
|
||||
const result = await this.authorizeService.signIn(state);
|
||||
this.message.next(undefined);
|
||||
switch (result.status) {
|
||||
case AuthenticationResultStatus.Redirect:
|
||||
// We replace the location here so that in case the user hits the back
|
||||
// arrow from within the login page he doesn't get into an infinite
|
||||
// redirect loop.
|
||||
window.location.replace(result.redirectUrl);
|
||||
break;
|
||||
case AuthenticationResultStatus.Success:
|
||||
await this.navigateToReturnUrl(returnUrl);
|
||||
break;
|
||||
case AuthenticationResultStatus.Fail:
|
||||
await this.router.navigate(ApplicationPaths.LoginFailedPathComponents, {
|
||||
queryParams: { [QueryParameterNames.Message]: result.message }
|
||||
});
|
||||
break;
|
||||
default:
|
||||
throw new Error(`Invalid status result ${(result as any).status}.`);
|
||||
}
|
||||
}
|
||||
|
||||
private async processLoginCallback(): Promise<void> {
|
||||
const url = window.location.href;
|
||||
const result = await this.authorizeService.completeSignIn(url);
|
||||
switch (result.status) {
|
||||
case AuthenticationResultStatus.Redirect:
|
||||
// There should not be any redirects as completeSignIn never redirects.
|
||||
throw new Error('Should not redirect.');
|
||||
case AuthenticationResultStatus.Success:
|
||||
await this.navigateToReturnUrl(this.getReturnUrl(result.state));
|
||||
break;
|
||||
case AuthenticationResultStatus.Fail:
|
||||
this.message.next(result.message);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private redirectToRegister(): any {
|
||||
this.redirectToApiAuthorizationPath(
|
||||
`${ApplicationPaths.IdentityRegisterPath}?returnUrl=${encodeURI('/' + ApplicationPaths.Login)}`);
|
||||
}
|
||||
|
||||
private redirectToProfile(): void {
|
||||
this.redirectToApiAuthorizationPath(ApplicationPaths.IdentityManagePath);
|
||||
}
|
||||
|
||||
private async navigateToReturnUrl(returnUrl: string) {
|
||||
// It's important that we do a replace here so that we remove the callback uri with the
|
||||
// fragment containing the tokens from the browser history.
|
||||
await this.router.navigateByUrl(returnUrl, {
|
||||
replaceUrl: true
|
||||
});
|
||||
}
|
||||
|
||||
private getReturnUrl(state?: INavigationState): string {
|
||||
const fromQuery = (this.activatedRoute.snapshot.queryParams as INavigationState).returnUrl;
|
||||
// If the url is comming from the query string, check that is either
|
||||
// a relative url or an absolute url
|
||||
if (fromQuery &&
|
||||
!(fromQuery.startsWith(`${window.location.origin}/`) ||
|
||||
/\/[^\/].*/.test(fromQuery))) {
|
||||
// This is an extra check to prevent open redirects.
|
||||
throw new Error('Invalid return url. The return url needs to have the same origin as the current page.');
|
||||
}
|
||||
return (state && state.returnUrl) ||
|
||||
fromQuery ||
|
||||
ApplicationPaths.DefaultLoginRedirectPath;
|
||||
}
|
||||
|
||||
private redirectToApiAuthorizationPath(apiAuthorizationPath: string) {
|
||||
// It's important that we do a replace here so that when the user hits the back arrow on the
|
||||
// browser he gets sent back to where it was on the app instead of to an endpoint on this
|
||||
// component.
|
||||
const redirectUrl = `${window.location.origin}${apiAuthorizationPath}`;
|
||||
window.location.replace(redirectUrl);
|
||||
}
|
||||
}
|
||||
|
||||
interface INavigationState {
|
||||
[ReturnUrlType]: string;
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
<p>{{ message | async }}</p>
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
|
||||
import { LogoutComponent } from './logout.component';
|
||||
|
||||
describe('LogoutComponent', () => {
|
||||
let component: LogoutComponent;
|
||||
let fixture: ComponentFixture<LogoutComponent>;
|
||||
|
||||
beforeEach(async(() => {
|
||||
TestBed.configureTestingModule({
|
||||
declarations: [ LogoutComponent ]
|
||||
})
|
||||
.compileComponents();
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = TestBed.createComponent(LogoutComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,117 @@
|
|||
import { Component, OnInit } from '@angular/core';
|
||||
import { AuthenticationResultStatus, AuthorizeService } from '../authorize.service';
|
||||
import { BehaviorSubject } from 'rxjs';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { take } from 'rxjs/operators';
|
||||
import { LogoutActions, ApplicationPaths, ReturnUrlType } from '../api-authorization.constants';
|
||||
|
||||
// The main responsibility of this component is to handle the user's logout process.
|
||||
// This is the starting point for the logout process, which is usually initiated when a
|
||||
// user clicks on the logout button on the LoginMenu component.
|
||||
@Component({
|
||||
selector: 'app-logout',
|
||||
templateUrl: './logout.component.html',
|
||||
styleUrls: ['./logout.component.css']
|
||||
})
|
||||
export class LogoutComponent implements OnInit {
|
||||
private message = new BehaviorSubject<string>(null);
|
||||
|
||||
constructor(
|
||||
private authorizeService: AuthorizeService,
|
||||
private activatedRoute: ActivatedRoute,
|
||||
private router: Router) { }
|
||||
|
||||
async ngOnInit() {
|
||||
const action = this.activatedRoute.snapshot.url[1];
|
||||
switch (action.path) {
|
||||
case LogoutActions.Logout:
|
||||
if (!!window.history.state.local) {
|
||||
await this.logout(this.getReturnUrl());
|
||||
} else {
|
||||
// This prevents regular links to <app>/authentication/logout from triggering a logout
|
||||
this.message.next('The logout was not initiated from within the page.');
|
||||
}
|
||||
|
||||
break;
|
||||
case LogoutActions.LogoutCallback:
|
||||
await this.processLogoutCallback();
|
||||
break;
|
||||
case LogoutActions.LoggedOut:
|
||||
this.message.next('You successfully logged out!');
|
||||
break;
|
||||
default:
|
||||
throw new Error(`Invalid action '${action}'`);
|
||||
}
|
||||
}
|
||||
|
||||
private async logout(returnUrl: string): Promise<void> {
|
||||
const state: INavigationState = { returnUrl };
|
||||
const isauthenticated = await this.authorizeService.isAuthenticated().pipe(
|
||||
take(1)
|
||||
).toPromise();
|
||||
if (isauthenticated) {
|
||||
const result = await this.authorizeService.signOut(state);
|
||||
switch (result.status) {
|
||||
case AuthenticationResultStatus.Redirect:
|
||||
// We replace the location here so that in case the user hits the back
|
||||
// arrow from within the IdP he doesn't get into an infinite redirect loop.
|
||||
window.location.replace(result.redirectUrl);
|
||||
break;
|
||||
case AuthenticationResultStatus.Success:
|
||||
await this.navigateToReturnUrl(returnUrl);
|
||||
break;
|
||||
case AuthenticationResultStatus.Fail:
|
||||
this.message.next(result.message);
|
||||
break;
|
||||
default:
|
||||
throw new Error('Invalid authentication result status.');
|
||||
}
|
||||
} else {
|
||||
this.message.next('You successfully logged out!');
|
||||
}
|
||||
}
|
||||
|
||||
private async processLogoutCallback(): Promise<void> {
|
||||
const url = window.location.href;
|
||||
const result = await this.authorizeService.completeSignOut(url);
|
||||
switch (result.status) {
|
||||
case AuthenticationResultStatus.Redirect:
|
||||
// There should not be any redirects as the only time completeAuthentication finishes
|
||||
// is when we are doing a redirect sign in flow.
|
||||
throw new Error('Should not redirect.');
|
||||
case AuthenticationResultStatus.Success:
|
||||
await this.navigateToReturnUrl(this.getReturnUrl(result.state));
|
||||
break;
|
||||
case AuthenticationResultStatus.Fail:
|
||||
this.message.next(result.message);
|
||||
break;
|
||||
default:
|
||||
throw new Error('Invalid authentication result status.');
|
||||
}
|
||||
}
|
||||
|
||||
private async navigateToReturnUrl(returnUrl: string) {
|
||||
await this.router.navigateByUrl(returnUrl, {
|
||||
replaceUrl: true
|
||||
});
|
||||
}
|
||||
|
||||
private getReturnUrl(state?: INavigationState): string {
|
||||
const fromQuery = (this.activatedRoute.snapshot.queryParams as INavigationState).returnUrl;
|
||||
// If the url is comming from the query string, check that is either
|
||||
// a relative url or an absolute url
|
||||
if (fromQuery &&
|
||||
!(fromQuery.startsWith(`${window.location.origin}/`) ||
|
||||
/\/[^\/].*/.test(fromQuery))) {
|
||||
// This is an extra check to prevent open redirects.
|
||||
throw new Error('Invalid return url. The return url needs to have the same origin as the current page.');
|
||||
}
|
||||
return (state && state.returnUrl) ||
|
||||
fromQuery ||
|
||||
ApplicationPaths.LoggedOut;
|
||||
}
|
||||
}
|
||||
|
||||
interface INavigationState {
|
||||
[ReturnUrlType]: string;
|
||||
}
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
import { BrowserModule } from '@angular/platform-browser';
|
||||
import { NgModule } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { HttpClientModule } from '@angular/common/http';
|
||||
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
|
||||
import { RouterModule } from '@angular/router';
|
||||
|
||||
import { AppComponent } from './app.component';
|
||||
|
|
@ -9,6 +9,11 @@ import { NavMenuComponent } from './nav-menu/nav-menu.component';
|
|||
import { HomeComponent } from './home/home.component';
|
||||
import { CounterComponent } from './counter/counter.component';
|
||||
import { FetchDataComponent } from './fetch-data/fetch-data.component';
|
||||
////#if (IndividualLocalAuth)
|
||||
import { ApiAuthorizationModule } from 'src/api-authorization/api-authorization.module';
|
||||
import { AuthorizeGuard } from 'src/api-authorization/authorize.guard';
|
||||
import { AuthorizeInterceptor } from 'src/api-authorization/authorize.interceptor';
|
||||
////#endif
|
||||
|
||||
@NgModule({
|
||||
declarations: [
|
||||
|
|
@ -22,13 +27,26 @@ import { FetchDataComponent } from './fetch-data/fetch-data.component';
|
|||
BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
|
||||
HttpClientModule,
|
||||
FormsModule,
|
||||
////#if (IndividualLocalAuth)
|
||||
ApiAuthorizationModule,
|
||||
////#endif
|
||||
RouterModule.forRoot([
|
||||
{ path: '', component: HomeComponent, pathMatch: 'full' },
|
||||
{ path: 'counter', component: CounterComponent },
|
||||
////#if (IndividualLocalAuth)
|
||||
{ path: 'fetch-data', component: FetchDataComponent, canActivate: [AuthorizeGuard] },
|
||||
////#else
|
||||
{ path: 'fetch-data', component: FetchDataComponent },
|
||||
////#endif
|
||||
])
|
||||
],
|
||||
////#if (IndividualLocalAuth)
|
||||
providers: [
|
||||
{ provide: HTTP_INTERCEPTORS, useClass: AuthorizeInterceptor, multi: true }
|
||||
],
|
||||
////#else
|
||||
providers: [],
|
||||
////#endif
|
||||
bootstrap: [AppComponent]
|
||||
})
|
||||
export class AppModule { }
|
||||
|
|
|
|||
|
|
@ -7,6 +7,9 @@
|
|||
<span class="navbar-toggler-icon"></span>
|
||||
</button>
|
||||
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse" [ngClass]='{"show": isExpanded}'>
|
||||
<!--#if (IndividualLocalAuth) -->
|
||||
<app-login-menu></app-login-menu>
|
||||
<!--#endif -->
|
||||
<ul class="navbar-nav flex-grow">
|
||||
<li class="nav-item" [routerLinkActive]='["link-active"]' [routerLinkActiveOptions]='{ exact: true }'>
|
||||
<a class="nav-link text-dark" [routerLink]='["/"]'>Home</a>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,22 @@
|
|||
using Microsoft.AspNetCore.ApiAuthorization.IdentityServer;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Company.WebApplication1.Controllers
|
||||
{
|
||||
public class OidcConfigurationController : Controller
|
||||
{
|
||||
public OidcConfigurationController(IClientRequestParametersProvider clientRequestParametersProvider)
|
||||
{
|
||||
ClientRequestParametersProvider = clientRequestParametersProvider;
|
||||
}
|
||||
|
||||
public IClientRequestParametersProvider ClientRequestParametersProvider { get; }
|
||||
|
||||
[HttpGet("_configuration/{clientId}")]
|
||||
public IActionResult GetClientRequestParameters([FromRoute]string clientId)
|
||||
{
|
||||
var parameters = ClientRequestParametersProvider.GetClientParameters(HttpContext, clientId);
|
||||
return Ok(parameters);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -3,9 +3,15 @@ using System.Collections.Generic;
|
|||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
#if (IndividualLocalAuth)
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
#endif
|
||||
|
||||
namespace Company.WebApplication1.Controllers
|
||||
{
|
||||
#if (IndividualLocalAuth)
|
||||
[Authorize]
|
||||
#endif
|
||||
[Route("api/[controller]")]
|
||||
public class SampleDataController : Controller
|
||||
{
|
||||
|
|
|
|||
|
|
@ -0,0 +1,21 @@
|
|||
using Company.WebApplication1.Models;
|
||||
using IdentityServer4.EntityFramework.Options;
|
||||
using Microsoft.AspNetCore.ApiAuthorization.IdentityServer;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Company.WebApplication1.Data
|
||||
{
|
||||
public class ApplicationDbContext : ApiAuthorizationDbContext<ApplicationUser>
|
||||
{
|
||||
public ApplicationDbContext(
|
||||
DbContextOptions options,
|
||||
IOptions<OperationalStoreOptions> operationalStoreOptions) : base(options, operationalStoreOptions)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue