diff --git a/src/Components/Server/src/Builder/ComponentEndpointConventionBuilderExtensions.cs b/src/Components/Server/src/Builder/ComponentEndpointConventionBuilderExtensions.cs new file mode 100644 index 000000000000..058a6ea94511 --- /dev/null +++ b/src/Components/Server/src/Builder/ComponentEndpointConventionBuilderExtensions.cs @@ -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 +{ + /// + /// Extensions for . + /// + public static class ComponentEndpointConventionBuilderExtensions + { + /// + /// Adds to the list of components registered with this instance. + /// + /// The component type. + /// The . + /// A CSS selector that identifies the DOM element into which the will be placed. + /// The . + public static IEndpointConventionBuilder AddComponent(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); + } + + /// + /// Adds to the list of components registered with this instance. + /// The selector will default to the component name in lowercase. + /// + /// The . + /// The component type. + /// The component selector in the DOM for the . + /// The . + 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 metadata, Type type, string selector) + { + metadata.Add(new ComponentDescriptor + { + ComponentType = type, + Selector = selector + }); + } + } +} diff --git a/src/Components/Server/src/Builder/ComponentEndpointRouteBuilderExtensions.cs b/src/Components/Server/src/Builder/ComponentEndpointRouteBuilderExtensions.cs new file mode 100644 index 000000000000..3284d3baf77e --- /dev/null +++ b/src/Components/Server/src/Builder/ComponentEndpointRouteBuilderExtensions.cs @@ -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 +{ + /// + /// Extensions for . + /// + public static class ComponentEndpointRouteBuilderExtensions + { + /// + /// Maps the SignalR to the path and associates + /// the component to this hub instance as the given DOM . + /// + /// The first associated with this . + /// The . + /// The selector for the . + /// The . + public static IEndpointConventionBuilder MapComponentHub( + 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); + } + + /// + /// Maps the SignalR to the path and associates + /// the component to this hub instance as the given DOM . + /// + /// The first associated with this . + /// The . + /// The selector for the . + /// The path to map to which the will be mapped. + /// The . + public static IEndpointConventionBuilder MapComponentHub( + 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); + } + + /// + /// Maps the SignalR to the path and associates + /// the component to this hub instance as the given DOM . + /// + /// The . + /// The first associated with this . + /// The selector for the . + /// The path to map to which the will be mapped. + /// The . + 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(path).AddComponent(componentType, selector); + } + } +} diff --git a/src/Components/Server/src/Builder/RazorComponentsApplicationBuilderExtensions.cs b/src/Components/Server/src/Builder/RazorComponentsApplicationBuilderExtensions.cs deleted file mode 100644 index f3a19d42123e..000000000000 --- a/src/Components/Server/src/Builder/RazorComponentsApplicationBuilderExtensions.cs +++ /dev/null @@ -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 -{ - /// - /// Extension methods to configure an for serving interactive components. - /// - public static class RazorComponentsApplicationBuilderExtensions - { - /// - /// Adds middleware for serving interactive Razor Components. - /// - /// The . - /// A components app startup type. - /// The . - public static IApplicationBuilder UseRazorComponents( - this IApplicationBuilder builder) - { - return UseRazorComponents(builder, null); - } - - /// - /// Adds middleware for serving interactive Razor Components. - /// - /// The . - /// A callback that can be used to configure the middleware. - /// A components app startup type. - /// The . - public static IApplicationBuilder UseRazorComponents( - this IApplicationBuilder builder, - Action 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.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"": [] }"); - }); - }); - } - } -} diff --git a/src/Components/Server/src/Builder/RazorComponentsOptions.cs b/src/Components/Server/src/Builder/RazorComponentsOptions.cs deleted file mode 100644 index c8399ed5e546..000000000000 --- a/src/Components/Server/src/Builder/RazorComponentsOptions.cs +++ /dev/null @@ -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 -{ - /// - /// Specifies options to configure - /// - public class RazorComponentsOptions - { - /// - /// 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 . - /// - public bool UseSignalRWithBlazorHub { get; set; } = true; - } -} diff --git a/src/Components/Server/src/Builder/ServerSideComponentsApplicationBuilder.cs b/src/Components/Server/src/Builder/ServerSideComponentsApplicationBuilder.cs deleted file mode 100644 index 3f42f189333f..000000000000 --- a/src/Components/Server/src/Builder/ServerSideComponentsApplicationBuilder.cs +++ /dev/null @@ -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)); - } - } -} diff --git a/src/Components/Server/src/Circuits/CircuitFactory.cs b/src/Components/Server/src/Circuits/CircuitFactory.cs index fbe4a8c7af14..ad51aa6ac58c 100644 --- a/src/Components/Server/src/Circuits/CircuitFactory.cs +++ b/src/Components/Server/src/Circuits/CircuitFactory.cs @@ -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); } } diff --git a/src/Components/Server/src/Circuits/CircuitHost.cs b/src/Components/Server/src/Circuits/CircuitHost.cs index b5d485b0e619..f5a1cfddb2f3 100644 --- a/src/Components/Server/src/Circuits/CircuitHost.cs +++ b/src/Components/Server/src/Circuits/CircuitHost.cs @@ -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 @@ internal class CircuitHost : IAsyncDisposable { private static readonly AsyncLocal _current = new AsyncLocal(); private readonly IServiceScope _scope; + private readonly IDispatcher _dispatcher; private readonly CircuitHandler[] _circuitHandlers; private bool _initialized; - private Action _configure; - /// /// Gets the current , if any. /// @@ -53,17 +52,19 @@ public CircuitHost( IClientProxy client, RendererRegistry rendererRegistry, RemoteRenderer renderer, - Action configure, + IList 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 @@ public CircuitHost( public Circuit Circuit { get; } - public IClientProxy Client { get; } + public IClientProxy Client { get; set; } public IJSRuntime JSRuntime { get; } @@ -85,21 +86,29 @@ public CircuitHost( public RendererRegistry RendererRegistry { get; } + public IList Descriptors { get; } + public IServiceProvider Services { get; } + public Task> 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); } diff --git a/src/Components/Server/src/Circuits/CircuitPrerenderer.cs b/src/Components/Server/src/Circuits/CircuitPrerenderer.cs new file mode 100644 index 000000000000..afa6e2c10eda --- /dev/null +++ b/src/Components/Server/src/Circuits/CircuitPrerenderer.cs @@ -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> 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); + } + } +} diff --git a/src/Components/Server/src/Circuits/DefaultCircuitFactory.cs b/src/Components/Server/src/Circuits/DefaultCircuitFactory.cs index 68bbef8d9df8..07150fa2d96a 100644 --- a/src/Components/Server/src/Circuits/DefaultCircuitFactory.cs +++ b/src/Components/Server/src/Circuits/DefaultCircuitFactory.cs @@ -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 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 components = ResolveComponentMetadata(httpContext, client); + + var scope = _scopeFactory.CreateScope(); + var encoder = scope.ServiceProvider.GetRequiredService(); + var jsRuntime = (RemoteJSRuntime)scope.ServiceProvider.GetRequiredService(); + if (client != null) { - var message = $"Could not find an ASP.NET Core Components startup action for request path '{httpContext.Request.Path}'."; - throw new InvalidOperationException(message); + jsRuntime.Initialize(client); + } + + var uriHelper = (RemoteUriHelper)scope.ServiceProvider.GetRequiredService(); + if (client != null) + { + uriHelper.Initialize(uriAbsolute, baseUriAbsolute, jsRuntime); + } + else + { + uriHelper.Initialize(uriAbsolute, baseUriAbsolute); } - var scope = _scopeFactory.CreateScope(); - var jsRuntime = new RemoteJSRuntime(client); var rendererRegistry = new RendererRegistry(); var dispatcher = Renderer.CreateDefaultDispatcher(); var renderer = new RemoteRenderer( @@ -53,6 +65,7 @@ public override CircuitHost CreateCircuitHost(HttpContext httpContext, IClientPr jsRuntime, client, dispatcher, + encoder, _loggerFactory.CreateLogger()); var circuitHandlers = scope.ServiceProvider.GetServices() @@ -64,15 +77,43 @@ public override CircuitHost CreateCircuitHost(HttpContext httpContext, IClientPr client, rendererRegistry, renderer, - config, + components, + dispatcher, jsRuntime, circuitHandlers); - // Initialize per-circuit data that services need - (circuitHost.Services.GetRequiredService() as DefaultJSRuntimeAccessor).JSRuntime = jsRuntime; + // Initialize per - circuit data that services need (circuitHost.Services.GetRequiredService() as DefaultCircuitAccessor).Circuit = circuitHost.Circuit; return circuitHost; } + + private static IList ResolveComponentMetadata(HttpContext httpContext, IClientProxy client) + { + if (client == null) + { + // This is the prerendering case. + return Array.Empty(); + } + else + { + var endpointFeature = httpContext.Features.Get(); + 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\"))' to register your hub."); + } + + var componentsMetadata = endpoint.Metadata.OfType().ToList(); + if (componentsMetadata.Count == 0) + { + throw new InvalidOperationException("No component was registered with the component hub."); + } + + return componentsMetadata; + } + } } } diff --git a/src/Components/Server/src/Circuits/DefaultCircuitFactoryOptions.cs b/src/Components/Server/src/Circuits/DefaultCircuitFactoryOptions.cs deleted file mode 100644 index d89494fe875b..000000000000 --- a/src/Components/Server/src/Circuits/DefaultCircuitFactoryOptions.cs +++ /dev/null @@ -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(...) - // callbacks to build up this dictionary mapping paths to startup actions - internal Dictionary> StartupActions { get; } - = new Dictionary>(); - } -} diff --git a/src/Components/Server/src/Circuits/DefaultJSRuntimeAccessor.cs b/src/Components/Server/src/Circuits/DefaultJSRuntimeAccessor.cs deleted file mode 100644 index a890098e9155..000000000000 --- a/src/Components/Server/src/Circuits/DefaultJSRuntimeAccessor.cs +++ /dev/null @@ -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; } - } -} diff --git a/src/Components/Server/src/Circuits/IJSRuntimeAccessor.cs b/src/Components/Server/src/Circuits/IJSRuntimeAccessor.cs deleted file mode 100644 index 023e39eef72e..000000000000 --- a/src/Components/Server/src/Circuits/IJSRuntimeAccessor.cs +++ /dev/null @@ -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; } - } -} diff --git a/src/Components/Server/src/Circuits/RemoteJSRuntime.cs b/src/Components/Server/src/Circuits/RemoteJSRuntime.cs index 3c9df0e7aff3..27bbacbe00f4 100644 --- a/src/Components/Server/src/Circuits/RemoteJSRuntime.cs +++ b/src/Components/Server/src/Circuits/RemoteJSRuntime.cs @@ -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); } } diff --git a/src/Components/Server/src/Circuits/RemoteRenderer.cs b/src/Components/Server/src/Circuits/RemoteRenderer.cs index 46d21e5fbf13..2e7c4044f3f8 100644 --- a/src/Components/Server/src/Circuits/RemoteRenderer.cs +++ b/src/Components/Server/src/Circuits/RemoteRenderer.cs @@ -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 @@ 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> _pendingRenders = new ConcurrentDictionary>(); private readonly ILogger _logger; private long _nextRenderId = 1; + private bool _prerenderMode; /// /// Notifies when a rendering exception occured. @@ -49,8 +51,9 @@ public RemoteRenderer( 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 @@ protected override void HandleException(Exception exception) } } + internal void StartPrerender() + { + _prerenderMode = true; + } + /// protected override void Dispose(bool disposing) { @@ -107,6 +115,14 @@ protected override void Dispose(bool disposing) /// 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 diff --git a/src/Components/Server/src/Circuits/RemoteUriHelper.cs b/src/Components/Server/src/Circuits/RemoteUriHelper.cs index 37bb8e79ccc1..c040d4efc992 100644 --- a/src/Components/Server/src/Circuits/RemoteUriHelper.cs +++ b/src/Components/Server/src/Circuits/RemoteUriHelper.cs @@ -14,15 +14,10 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits /// public class RemoteUriHelper : UriHelperBase { - private readonly IJSRuntime _jsRuntime; + private IJSRuntime _jsRuntime; - /// - /// Creates a new . - /// - /// - public RemoteUriHelper(IJSRuntime jsRuntime) + public RemoteUriHelper() { - _jsRuntime = jsRuntime; } /// @@ -30,18 +25,38 @@ public RemoteUriHelper(IJSRuntime jsRuntime) /// /// The absolute URI of the current page. /// The absolute base URI of the current page. + /// The to use for interoperability. public void Initialize(string uriAbsolute, string baseUriAbsolute) { SetAbsoluteBaseUri(baseUriAbsolute); SetAbsoluteUri(uriAbsolute); TriggerOnLocationChanged(); + } + + /// + /// Initializes the . + /// + /// The absolute URI of the current page. + /// The absolute base URI of the current page. + /// The to use for interoperability. + 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( - Interop.EnableNavigationInterception, - typeof(RemoteUriHelper).Assembly.GetName().Name, - nameof(NotifyLocationChanged)); + Interop.EnableNavigationInterception, + typeof(RemoteUriHelper).Assembly.GetName().Name, + nameof(NotifyLocationChanged)); } + /// /// For framework use only. /// @@ -61,9 +76,12 @@ public static void NotifyLocationChanged(string uriAbsolute) uriHelper.TriggerOnLocationChanged(); } - /// protected override void NavigateToCore(string uri, bool forceLoad) { + if (_jsRuntime == null) + { + throw new InvalidOperationException("Navigation is not allowed during prerendering."); + } _jsRuntime.InvokeAsync(Interop.NavigateTo, uri, forceLoad); } } diff --git a/src/Components/Server/src/ComponentsHub.cs b/src/Components/Server/src/ComponentHub.cs similarity index 92% rename from src/Components/Server/src/ComponentsHub.cs rename to src/Components/Server/src/ComponentHub.cs index 946af953f0dd..b23ec10fa811 100644 --- a/src/Components/Server/src/ComponentsHub.cs +++ b/src/Components/Server/src/ComponentHub.cs @@ -15,7 +15,7 @@ namespace Microsoft.AspNetCore.Components.Server /// /// A SignalR hub that accepts connections to an ASP.NET Core Components application. /// - 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 @@ public sealed class ComponentsHub : Hub /// Intended for framework use only. Applications should not instantiate /// this class directly. /// - public ComponentsHub(IServiceProvider services, ILogger logger) + public ComponentHub(IServiceProvider services, ILogger logger) { _circuitFactory = services.GetRequiredService(); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); @@ -58,11 +58,13 @@ public override async Task OnDisconnectedAsync(Exception exception) /// 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(); - 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); diff --git a/src/Components/Server/src/DependencyInjection/ComponentDescriptor.cs b/src/Components/Server/src/DependencyInjection/ComponentDescriptor.cs new file mode 100644 index 000000000000..30c63199742f --- /dev/null +++ b/src/Components/Server/src/DependencyInjection/ComponentDescriptor.cs @@ -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; + } + } +} diff --git a/src/Components/Server/src/DependencyInjection/ComponentServiceCollectionExtensions.cs b/src/Components/Server/src/DependencyInjection/ComponentServiceCollectionExtensions.cs new file mode 100644 index 000000000000..628e579ad527 --- /dev/null +++ b/src/Components/Server/src/DependencyInjection/ComponentServiceCollectionExtensions.cs @@ -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 +{ + /// + /// Extension methods to configure an for components. + /// + public static class ComponentServiceCollectionExtensions + { + /// + /// Adds Razor Component app services to the service collection. + /// + /// The . + /// The . + 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, ConfigureStaticFilesOptions>()); + services.TryAddSingleton(); + services.TryAddScoped(s => s.GetRequiredService().Circuit); + services.TryAddScoped(); + + // 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(); + + // Standard razor component services implementations + services.AddScoped(); + services.AddScoped(); + + return services; + } + } +} diff --git a/src/Components/Server/src/DependencyInjection/ConfigureStaticFilesOptions.cs b/src/Components/Server/src/DependencyInjection/ConfigureStaticFilesOptions.cs new file mode 100644 index 000000000000..650ac46502eb --- /dev/null +++ b/src/Components/Server/src/DependencyInjection/ConfigureStaticFilesOptions.cs @@ -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 + { + 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); + } + } + } + } +} diff --git a/src/Components/Server/src/DependencyInjection/RazorComponentsServiceCollectionExtensions.cs b/src/Components/Server/src/DependencyInjection/RazorComponentsServiceCollectionExtensions.cs deleted file mode 100644 index 51c29bbefe9d..000000000000 --- a/src/Components/Server/src/DependencyInjection/RazorComponentsServiceCollectionExtensions.cs +++ /dev/null @@ -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 -{ - /// - /// Extension methods to configure an for interactive components. - /// - public static class RazorComponentsServiceCollectionExtensions - { - /// - /// Adds Razor Component services to the service collection. - /// - /// The . - /// A Razor Components project startup type. - /// The . - 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); - } - - /// - /// Adds Razor Component app services to the service collection. - /// - /// The . - /// A Components app startup type. - /// The . - public static IServiceCollection AddRazorComponents( - 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(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(); - services.TryAddScoped(); - services.TryAddScoped(s => s.GetRequiredService().Circuit); - services.TryAddScoped(); - services.TryAddScoped(s => s.GetRequiredService().JSRuntime); - services.TryAddScoped(); - - // 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(); - } - } -} diff --git a/src/Components/Server/src/Microsoft.AspNetCore.Components.Server.csproj b/src/Components/Server/src/Microsoft.AspNetCore.Components.Server.csproj index 7cccc2529f6b..e36e4e749508 100644 --- a/src/Components/Server/src/Microsoft.AspNetCore.Components.Server.csproj +++ b/src/Components/Server/src/Microsoft.AspNetCore.Components.Server.csproj @@ -1,4 +1,4 @@ - + netcoreapp3.0 @@ -30,7 +30,7 @@ - + diff --git a/src/Components/Server/test/Circuits/CircuitHostTest.cs b/src/Components/Server/test/Circuits/CircuitHostTest.cs index 60efec07cb21..317fe36a283f 100644 --- a/src/Components/Server/test/Circuits/CircuitHostTest.cs +++ b/src/Components/Server/test/Circuits/CircuitHostTest.cs @@ -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 @@ public async Task DisposeAsync_DisposesResources() { // Arrange var serviceScope = new Mock(); - var remoteRenderer = GetRemoteRenderer(); + var remoteRenderer = GetRemoteRenderer(Renderer.CreateDefaultDispatcher()); var circuitHost = GetCircuitHost( serviceScope.Object, remoteRenderer); @@ -130,8 +133,8 @@ private static CircuitHost GetCircuitHost( var clientProxy = Mock.Of(); var renderRegistry = new RendererRegistry(); var jsRuntime = Mock.Of(); - - remoteRenderer = remoteRenderer ?? GetRemoteRenderer(); + var dispatcher = Renderer.CreateDefaultDispatcher(); + remoteRenderer = remoteRenderer ?? GetRemoteRenderer(dispatcher); handlers = handlers ?? Array.Empty(); return new CircuitHost( @@ -139,24 +142,26 @@ private static CircuitHost GetCircuitHost( clientProxy, renderRegistry, remoteRenderer, - configure: _ => { }, + new List(), + dispatcher, jsRuntime: jsRuntime, handlers); } - private static TestRemoteRenderer GetRemoteRenderer() + private static TestRemoteRenderer GetRemoteRenderer(IDispatcher dispatcher) { return new TestRemoteRenderer( Mock.Of(), new RendererRegistry(), + dispatcher, Mock.Of(), Mock.Of()); } 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) { } diff --git a/src/Components/test/E2ETest/Infrastructure/SeleniumStandaloneServer.cs b/src/Components/test/E2ETest/Infrastructure/SeleniumStandaloneServer.cs index 46c88f103f43..9bcfe55d6f32 100644 --- a/src/Components/test/E2ETest/Infrastructure/SeleniumStandaloneServer.cs +++ b/src/Components/test/E2ETest/Infrastructure/SeleniumStandaloneServer.cs @@ -126,7 +126,7 @@ void LogOutput(object sender, DataReceivedEventArgs e) 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()); } } diff --git a/src/Components/test/testassets/ComponentsApp.App/Shared/MainLayout.cshtml b/src/Components/test/testassets/ComponentsApp.App/Shared/MainLayout.cshtml index 902e3edb0855..ecd956e1d1b5 100644 --- a/src/Components/test/testassets/ComponentsApp.App/Shared/MainLayout.cshtml +++ b/src/Components/test/testassets/ComponentsApp.App/Shared/MainLayout.cshtml @@ -5,9 +5,9 @@
-
+ @*
About -
+
*@
@Body diff --git a/src/Components/test/testassets/ComponentsApp.Server/ComponentsApp.Server.csproj b/src/Components/test/testassets/ComponentsApp.Server/ComponentsApp.Server.csproj index be50b6a49919..6fa0b66dc386 100644 --- a/src/Components/test/testassets/ComponentsApp.Server/ComponentsApp.Server.csproj +++ b/src/Components/test/testassets/ComponentsApp.Server/ComponentsApp.Server.csproj @@ -10,6 +10,7 @@ + diff --git a/src/Components/test/testassets/ComponentsApp.Server/wwwroot/index.html b/src/Components/test/testassets/ComponentsApp.Server/Pages/Index.cshtml similarity index 78% rename from src/Components/test/testassets/ComponentsApp.Server/wwwroot/index.html rename to src/Components/test/testassets/ComponentsApp.Server/Pages/Index.cshtml index b432fd88f8c3..9988e733aedd 100644 --- a/src/Components/test/testassets/ComponentsApp.Server/wwwroot/index.html +++ b/src/Components/test/testassets/ComponentsApp.Server/Pages/Index.cshtml @@ -1,3 +1,6 @@ +@page "{*clientroutes}" +@using ComponentsApp.App + @@ -9,7 +12,7 @@ - Loading... + @(await Html.RenderComponentAsync()) diff --git a/src/Components/test/testassets/ComponentsApp.Server/Startup.cs b/src/Components/test/testassets/ComponentsApp.Server/Startup.cs index f269649446b0..62479bc3990c 100644 --- a/src/Components/test/testassets/ComponentsApp.Server/Startup.cs +++ b/src/Components/test/testassets/ComponentsApp.Server/Startup.cs @@ -14,8 +14,10 @@ public class Startup { public void ConfigureServices(IServiceCollection services) { + services.AddMvc(); services.AddSingleton(); - services.AddRazorComponents(); + services.AddRazorComponents(); + services.AddSingleton(); } @@ -27,7 +29,11 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env) } app.UseStaticFiles(); - app.UseRazorComponents(); + app.UseRouting(builder => + { + builder.MapRazorPages(); + builder.MapComponentHub("app"); + }); } } } diff --git a/src/Components/test/testassets/TestServer/Startup.cs b/src/Components/test/testassets/TestServer/Startup.cs index 7b740845be64..87a1c1c2572e 100644 --- a/src/Components/test/testassets/TestServer/Startup.cs +++ b/src/Components/test/testassets/TestServer/Startup.cs @@ -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 @@ public void ConfigureServices(IServiceCollection services) { options.AddPolicy("AllowAll", _ => { /* Controlled below */ }); }); - services.AddRazorComponents(); + services.AddRazorComponents(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. @@ -47,8 +49,12 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env) // 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.DefaultPath)); - subdirApp.UseBlazor(); + subdirApp.UseRouting(routes => + routes.MapHub(ComponentHub.DefaultPath).AddComponent(selector: "root")); + + subdirApp.MapWhen( + ctx => ctx.Features.Get()?.Endpoint == null, + blazorBuilder => blazorBuilder.UseBlazor()); }); } diff --git a/src/Mvc/Mvc.ViewFeatures/src/DependencyInjection/MvcViewFeaturesMvcCoreBuilderExtensions.cs b/src/Mvc/Mvc.ViewFeatures/src/DependencyInjection/MvcViewFeaturesMvcCoreBuilderExtensions.cs index 9ef038271dc3..285ba5aec58d 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/DependencyInjection/MvcViewFeaturesMvcCoreBuilderExtensions.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/DependencyInjection/MvcViewFeaturesMvcCoreBuilderExtensions.cs @@ -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.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 @@ internal static void AddViewServices(IServiceCollection services) ServiceDescriptor.Transient()); services.TryAddSingleton(); + // + // Component prerendering + // + services.TryAddSingleton(); + services.TryAddScoped(); + services.TryAddScoped(); services.TryAddTransient(); diff --git a/src/Mvc/Mvc.ViewFeatures/src/HtmlHelperComponentExtensions.cs b/src/Mvc/Mvc.ViewFeatures/src/HtmlHelperRazorComponentExtensions.cs similarity index 53% rename from src/Mvc/Mvc.ViewFeatures/src/HtmlHelperComponentExtensions.cs rename to src/Mvc/Mvc.ViewFeatures/src/HtmlHelperRazorComponentExtensions.cs index e6af6078c992..50f3fc58aced 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/HtmlHelperComponentExtensions.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/HtmlHelperRazorComponentExtensions.cs @@ -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 /// /// Extensions for rendering components. /// - public static class HtmlHelperComponentExtensions + public static class HtmlHelperRazorComponentExtensions { /// /// Renders the . @@ -27,7 +26,7 @@ public static Task RenderComponentAsync(this IHtmlHelp { if (htmlHelper == null) { - throw new System.ArgumentNullException(nameof(htmlHelper)); + throw new ArgumentNullException(nameof(htmlHelper)); } return htmlHelper.RenderComponentAsync(null); @@ -46,39 +45,21 @@ public static async Task RenderComponentAsync( { if (htmlHelper == null) { - throw new System.ArgumentNullException(nameof(htmlHelper)); + throw new ArgumentNullException(nameof(htmlHelper)); } - var serviceProvider = htmlHelper.ViewContext.HttpContext.RequestServices; - var encoder = serviceProvider.GetRequiredService(); - var dispatcher = Renderer.CreateDefaultDispatcher(); - using (var htmlRenderer = new HtmlRenderer(serviceProvider, encoder.Encode, dispatcher)) - { - var result = await dispatcher.InvokeAsync(() => htmlRenderer.RenderComponentAsync( - parameters == null ? - ParameterCollection.Empty : - ParameterCollection.FromDictionary(HtmlHelper.ObjectToDictionary(parameters)))); + var httpContext = htmlHelper.ViewContext.HttpContext; + var serviceProvider = httpContext.RequestServices; + var prerenderer = serviceProvider.GetRequiredService(); - return new ComponentHtmlContent(result); - } - } - - private class ComponentHtmlContent : IHtmlContent - { - private readonly IEnumerable _componentResult; - - public ComponentHtmlContent(IEnumerable componentResult) + var result = await prerenderer.PrerenderComponentAsync(new ComponentPrerenderingContext { - _componentResult = componentResult; - } + Context = httpContext, + ComponentType = typeof(TComponent), + Parameters = parameters == null ? ParameterCollection.Empty : ParameterCollection.FromDictionary(HtmlHelper.ObjectToDictionary(parameters)) + }); - public void WriteTo(TextWriter writer, HtmlEncoder encoder) - { - foreach (var element in _componentResult) - { - writer.Write(element); - } - } + return new ComponentHtmlContent(result); } } } diff --git a/src/Mvc/Mvc.ViewFeatures/src/Infrastructure/ComponentHtmlContent.cs b/src/Mvc/Mvc.ViewFeatures/src/Infrastructure/ComponentHtmlContent.cs new file mode 100644 index 000000000000..d91e80d1239d --- /dev/null +++ b/src/Mvc/Mvc.ViewFeatures/src/Infrastructure/ComponentHtmlContent.cs @@ -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 _componentResult; + + public ComponentHtmlContent(IEnumerable componentResult) + { + _componentResult = componentResult; + } + + public void WriteTo(TextWriter writer, HtmlEncoder encoder) + { + foreach (var element in _componentResult) + { + writer.Write(element); + } + } + } +} diff --git a/src/Mvc/Mvc.ViewFeatures/src/Infrastructure/HttpUriHelper.cs b/src/Mvc/Mvc.ViewFeatures/src/Infrastructure/HttpUriHelper.cs new file mode 100644 index 000000000000..15cef58c04e1 --- /dev/null +++ b/src/Mvc/Mvc.ViewFeatures/src/Infrastructure/HttpUriHelper.cs @@ -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."); + } + } +} diff --git a/src/Mvc/Mvc.ViewFeatures/src/Infrastructure/UnsupportedJavaScriptRuntime.cs b/src/Mvc/Mvc.ViewFeatures/src/Infrastructure/UnsupportedJavaScriptRuntime.cs new file mode 100644 index 000000000000..540a2dcb9ea7 --- /dev/null +++ b/src/Mvc/Mvc.ViewFeatures/src/Infrastructure/UnsupportedJavaScriptRuntime.cs @@ -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 InvokeAsync(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."); + } + } +} diff --git a/src/Mvc/Mvc.ViewFeatures/src/RazorComponents/MvcRazorComponentPrerenderer.cs b/src/Mvc/Mvc.ViewFeatures/src/RazorComponents/MvcRazorComponentPrerenderer.cs new file mode 100644 index 000000000000..8f39ffa2ab62 --- /dev/null +++ b/src/Mvc/Mvc.ViewFeatures/src/RazorComponents/MvcRazorComponentPrerenderer.cs @@ -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> 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(); + helper.InitializeState(context.Context); + using (var htmlRenderer = new HtmlRenderer(context.Context.RequestServices, _encoder.Encode, dispatcher)) + { + return await dispatcher.InvokeAsync(() => htmlRenderer.RenderComponentAsync( + context.ComponentType, + parameters)); + } + } + } +} diff --git a/src/Mvc/Mvc.ViewFeatures/src/RazorComponents/Prerendering/ComponentPrerrenderingContext.cs b/src/Mvc/Mvc.ViewFeatures/src/RazorComponents/Prerendering/ComponentPrerrenderingContext.cs new file mode 100644 index 000000000000..26bb6326bd55 --- /dev/null +++ b/src/Mvc/Mvc.ViewFeatures/src/RazorComponents/Prerendering/ComponentPrerrenderingContext.cs @@ -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 +{ + /// + /// The context for prerendering a component. + /// + public class ComponentPrerenderingContext + { + /// + /// Gets or sets the component type. + /// + public Type ComponentType { get; set; } + + /// + /// Gets or sets the parameters for the component. + /// + public ParameterCollection Parameters { get; set; } + + /// + /// Gets or sets the in which the prerendering has been initiated. + /// + public HttpContext Context { get; set; } + } +} diff --git a/src/Mvc/Mvc.ViewFeatures/src/RazorComponents/Prerendering/IComponentPrerenderer.cs b/src/Mvc/Mvc.ViewFeatures/src/RazorComponents/Prerendering/IComponentPrerenderer.cs new file mode 100644 index 000000000000..24480d0aa030 --- /dev/null +++ b/src/Mvc/Mvc.ViewFeatures/src/RazorComponents/Prerendering/IComponentPrerenderer.cs @@ -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 +{ + /// + /// Prerrenders instances. + /// + public interface IComponentPrerenderer + { + /// + /// Prerrenders the component . + /// + /// The context in which the prerrendering is happening. + /// that will complete when the prerendering is done. + Task> PrerenderComponentAsync(ComponentPrerenderingContext context); + } +} diff --git a/src/Mvc/Mvc.ViewFeatures/test/HtmlHelperComponentExtensionsTests.cs b/src/Mvc/Mvc.ViewFeatures/test/HtmlHelperComponentExtensionsTests.cs index b9439dbae1c2..014c5c200157 100644 --- a/src/Mvc/Mvc.ViewFeatures/test/HtmlHelperComponentExtensionsTests.cs +++ b/src/Mvc/Mvc.ViewFeatures/test/HtmlHelperComponentExtensionsTests.cs @@ -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 @@ public async Task CanRender_ComponentWithParametersObject() Assert.Equal("

Hello Steve!

", content); } + [Fact] + public async Task CanCatch_ComponentWithSynchronousException() + { + // Arrange + var helper = CreateHelper(); + + // Act & Assert + var exception = await Assert.ThrowsAsync(() => helper.RenderComponentAsync(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(() => helper.RenderComponentAsync(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(() => helper.RenderComponentAsync(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(() => helper.RenderComponentAsync(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 @@ public async Task CanRender_AsyncComponent() 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 configureServices = null) + private static IHtmlHelper CreateHelper(HttpContext ctx = null, Action configureServices = null) { - var serviceCollection = new ServiceCollection(); - serviceCollection.AddSingleton(HtmlEncoder.Default); - configureServices?.Invoke(serviceCollection); + var services = new ServiceCollection(); + services.AddSingleton(HtmlEncoder.Default); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + + configureServices?.Invoke(services); var helper = new Mock(); + 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 @@ public Task SetParametersAsync(ParameterCollection parameters) } } + 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("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; } diff --git a/src/Mvc/test/Mvc.FunctionalTests/BasicTests.cs b/src/Mvc/test/Mvc.FunctionalTests/BasicTests.cs index 33b3355ce6ce..ff4ac8348a9e 100644 --- a/src/Mvc/test/Mvc.FunctionalTests/BasicTests.cs +++ b/src/Mvc/test/Mvc.FunctionalTests/BasicTests.cs @@ -481,6 +481,9 @@ public async Task ApplicationAssemblyPartIsListedAsFirstAssembly() var expected = new[] { "BasicWebSite", + "Microsoft.AspNetCore.Components.Server", + "Microsoft.AspNetCore.SpaServices", + "Microsoft.AspNetCore.SpaServices.Extensions", "Microsoft.AspNetCore.Mvc.TagHelpers", "Microsoft.AspNetCore.Mvc.Razor", }; diff --git a/src/Mvc/test/Mvc.FunctionalTests/ComponentRenderingFunctionalTests.cs b/src/Mvc/test/Mvc.FunctionalTests/ComponentRenderingFunctionalTests.cs index 6e3ccce52856..dbbdd61985ee 100644 --- a/src/Mvc/test/Mvc.FunctionalTests/ComponentRenderingFunctionalTests.cs +++ b/src/Mvc/test/Mvc.FunctionalTests/ComponentRenderingFunctionalTests.cs @@ -5,6 +5,7 @@ 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 @@ public class ComponentRenderingFunctionalTests : IClassFixture fixture) { + Factory = fixture; Client = Client ?? CreateClient(fixture); } public HttpClient Client { get; } + public MvcTestFixture Factory { get; } + [Fact] public async Task Renders_BasicComponent() { @@ -33,6 +37,53 @@ public async Task Renders_BasicComponent() AssertComponent("\n

Hello world!

\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

Hello world!

\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

Routed successfully

\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

Routed successfully

\n", "Routing", content); + } + [Fact] public async Task Renders_AsyncComponent() { diff --git a/src/Mvc/test/WebSites/BasicWebSite/BasicWebSite.csproj b/src/Mvc/test/WebSites/BasicWebSite/BasicWebSite.csproj index 97ef847b07ff..89b48fe417b1 100644 --- a/src/Mvc/test/WebSites/BasicWebSite/BasicWebSite.csproj +++ b/src/Mvc/test/WebSites/BasicWebSite/BasicWebSite.csproj @@ -15,6 +15,7 @@ + diff --git a/src/Mvc/test/WebSites/BasicWebSite/Controllers/ComponentsController.cs b/src/Mvc/test/WebSites/BasicWebSite/Controllers/RazorComponentsController.cs similarity index 95% rename from src/Mvc/test/WebSites/BasicWebSite/Controllers/ComponentsController.cs rename to src/Mvc/test/WebSites/BasicWebSite/Controllers/RazorComponentsController.cs index 99ba2690ee17..c499c5f345c5 100644 --- a/src/Mvc/test/WebSites/BasicWebSite/Controllers/ComponentsController.cs +++ b/src/Mvc/test/WebSites/BasicWebSite/Controllers/RazorComponentsController.cs @@ -9,7 +9,7 @@ namespace BasicWebSite.Controllers { - public class ComponentsController : Controller + public class RazorComponentsController : Controller { private static WeatherRow[] _weatherData = new[] { @@ -51,6 +51,7 @@ public class ComponentsController : Controller }; [HttpGet("/components")] + [HttpGet("/components/routable")] public IActionResult Index() { return View(); diff --git a/src/Mvc/test/WebSites/BasicWebSite/RazorComponents/Fallback.razor b/src/Mvc/test/WebSites/BasicWebSite/RazorComponents/Fallback.razor new file mode 100644 index 000000000000..ff7cde246bd2 --- /dev/null +++ b/src/Mvc/test/WebSites/BasicWebSite/RazorComponents/Fallback.razor @@ -0,0 +1 @@ +

Route not found

\ No newline at end of file diff --git a/src/Mvc/test/WebSites/BasicWebSite/RazorComponents/RoutedPage.razor b/src/Mvc/test/WebSites/BasicWebSite/RazorComponents/RoutedPage.razor new file mode 100644 index 000000000000..7e2dbffeac5c --- /dev/null +++ b/src/Mvc/test/WebSites/BasicWebSite/RazorComponents/RoutedPage.razor @@ -0,0 +1,2 @@ +@page "/components/routable" +

Routed successfully

diff --git a/src/Mvc/test/WebSites/BasicWebSite/RazorComponents/RouterContainer.razor b/src/Mvc/test/WebSites/BasicWebSite/RazorComponents/RouterContainer.razor new file mode 100644 index 000000000000..ab5e66e9c229 --- /dev/null +++ b/src/Mvc/test/WebSites/BasicWebSite/RazorComponents/RouterContainer.razor @@ -0,0 +1,5 @@ +Router component + + \ No newline at end of file diff --git a/src/Mvc/test/WebSites/BasicWebSite/Views/Components/Index.cshtml b/src/Mvc/test/WebSites/BasicWebSite/Views/RazorComponents/Index.cshtml similarity index 76% rename from src/Mvc/test/WebSites/BasicWebSite/Views/Components/Index.cshtml rename to src/Mvc/test/WebSites/BasicWebSite/Views/RazorComponents/Index.cshtml index 6bff9af76fe0..8a0211c49816 100644 --- a/src/Mvc/test/WebSites/BasicWebSite/Views/Components/Index.cshtml +++ b/src/Mvc/test/WebSites/BasicWebSite/Views/RazorComponents/Index.cshtml @@ -6,4 +6,8 @@
@(await Html.RenderComponentAsync(new { StartDate = new DateTime(2019, 01, 15) })) +
+ +
+ @(await Html.RenderComponentAsync())
\ No newline at end of file diff --git a/src/ProjectTemplates/Web.ProjectTemplates/RazorComponentsWeb-CSharp.csproj.in b/src/ProjectTemplates/Web.ProjectTemplates/RazorComponentsWeb-CSharp.csproj.in index a592f9149553..90f398d369bf 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/RazorComponentsWeb-CSharp.csproj.in +++ b/src/ProjectTemplates/Web.ProjectTemplates/RazorComponentsWeb-CSharp.csproj.in @@ -10,6 +10,7 @@ + diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/RazorComponentsWeb-CSharp/Components/Startup.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/RazorComponentsWeb-CSharp/Components/Startup.cs deleted file mode 100644 index 760f618a75c7..000000000000 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/RazorComponentsWeb-CSharp/Components/Startup.cs +++ /dev/null @@ -1,12 +0,0 @@ -using Microsoft.AspNetCore.Components.Builder; - -namespace RazorComponentsWeb_CSharp.Components -{ - public class Startup - { - public void Configure(IComponentsApplicationBuilder app) - { - app.AddComponent("app"); - } - } -} diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/RazorComponentsWeb-CSharp/wwwroot/index.html b/src/ProjectTemplates/Web.ProjectTemplates/content/RazorComponentsWeb-CSharp/Pages/Index.cshtml similarity index 83% rename from src/ProjectTemplates/Web.ProjectTemplates/content/RazorComponentsWeb-CSharp/wwwroot/index.html rename to src/ProjectTemplates/Web.ProjectTemplates/content/RazorComponentsWeb-CSharp/Pages/Index.cshtml index dbec2f1a8fad..d3cc00f32c3e 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/RazorComponentsWeb-CSharp/wwwroot/index.html +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/RazorComponentsWeb-CSharp/Pages/Index.cshtml @@ -1,3 +1,4 @@ +@page "{*clientPath}" @@ -9,7 +10,7 @@ - Loading... + @(await Html.RenderComponentAsync()) diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/RazorComponentsWeb-CSharp/Pages/_ViewImports.cshtml b/src/ProjectTemplates/Web.ProjectTemplates/content/RazorComponentsWeb-CSharp/Pages/_ViewImports.cshtml new file mode 100644 index 000000000000..a7aad3ea3627 --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/RazorComponentsWeb-CSharp/Pages/_ViewImports.cshtml @@ -0,0 +1,3 @@ +@using RazorComponentsWeb_CSharp.Components +@namespace RazorComponentsWeb_CSharp.Pages +@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/RazorComponentsWeb-CSharp/Startup.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/RazorComponentsWeb-CSharp/Startup.cs index 7854291ea984..f35edd4c14fb 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/RazorComponentsWeb-CSharp/Startup.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/RazorComponentsWeb-CSharp/Startup.cs @@ -10,6 +10,7 @@ #endif using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using RazorComponentsWeb_CSharp.Components; using RazorComponentsWeb_CSharp.Services; namespace RazorComponentsWeb_CSharp @@ -20,8 +21,12 @@ public class Startup // 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(); - services.AddRazorComponents(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. @@ -43,7 +48,12 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env) app.UseHttpsRedirection(); #endif app.UseStaticFiles(); - app.UseRazorComponents(); + + app.UseRouting(routes => + { + routes.MapRazorPages(); + routes.MapComponentHub("app"); + }); } } }