Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Blazor .NET8 right approach for having everything in wasm but at the same time also have a support for server page rendering for certain pages

$
0
0

Goal/constraint is to have a SPA, everything in wasm (even router) but at the same time support pages on the server.

Here I accomplished rendering rules by page locations:

  • If page is on client only, it will render InteractiveWebAssemblyRenderMode without prerender.
  • If page is on server only, it will render InteractiveServerRenderMode.
  • If page is on server and client, it will render InteractiveWebAssemblyRenderMode with prerender.

Pages on server that are also on client will be added as a link from the client.

Components on server:

Program.cs:

...app.MapRazorComponents<App>()    .AddInteractiveServerRenderMode()    .AddInteractiveWebAssemblyRenderMode();app.Use404FallbackToClient();app.Run();

ApplicationBuilderExtensions.cs:

public static void Use404FallbackToClient(this IApplicationBuilder builder){    builder.Use(async (context, next) =>    {        await next();        // Check if the response status code is 404 and the request path doesn't start with "/_framework"        if (context.Response.StatusCode == StatusCodes.Status404NotFound && !context.Request.Path.StartsWithSegments("/_framework"))        {            // Create a new endpoint for the Razor component rendering            var endpointFeature = context.Features.Get<IEndpointFeature>();            if (endpointFeature != null)            {                endpointFeature.Endpoint = new RouteEndpoint(                    async httpContext =>                    {                        context.Response.StatusCode = StatusCodes.Status200OK;                        // Render the Blazor component (in this case, App or your custom component)                        var result = new RazorComponentResult<App>();                        await result.ExecuteAsync(httpContext);                    },                    RoutePatternFactory.Parse("/404"),                    0,                    new EndpointMetadataCollection(new[] { new ComponentTypeMetadata(typeof(_404)) }),"404 Endpoint"                );            }            // Render the Razor component directly            await endpointFeature.Endpoint.RequestDelegate(context);        }    });}

App.razor:

<!DOCTYPE html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><base href="/" /><link rel="stylesheet" href="bootstrap/bootstrap.min.css" /><link rel="stylesheet" href="app.css" /><link rel="stylesheet" href="Sindikat.Web.styles.css" /><link rel="icon" type="image/png" href="favicon.png" /><HeadOutlet @rendermode="RenderModeForPage" /><RadzenTheme Theme="material" @rendermode="RenderModeForPage" /></head><body><Routes @rendermode="RenderModeForPage" /><script src="_framework/blazor.web.js"></script><script src="_content/Radzen.Blazor/Radzen.Blazor.js?v=@(typeof(Radzen.Colors).Assembly.GetName().Version)"></script><script src="js/sindikatAppBundle.js"></script></body></html>    public partial class App    {        private static Assembly serverAssembly;        static App()        {            serverAssembly = typeof(Program).Assembly;        }        [CascadingParameter]        private HttpContext HttpContext { get; set; } = default!;        private IComponentRenderMode? RenderModeForPage { get; set; }        protected override void OnInitialized()        {            var endpointFeature = HttpContext.Features.Get<IEndpointFeature>();            var type = endpointFeature.Endpoint?.Metadata.GetMetadata<ComponentTypeMetadata>()?.Type;            var serverPage = type?.Assembly == serverAssembly;            var clientAssembly = typeof(Sindikat.Web.Client.ModuleDefinitions.Module).Assembly;            var clientPageType = clientAssembly.GetType($"Sindikat.Web.Client.Components.Pages.{type.Name}");            var serverOnlyPage = serverPage && clientPageType == null;          RenderModeForPage = serverOnlyPage ?            null :            new InteractiveWebAssemblyRenderMode();        }    }

Components on Client:

Home.razor:

I decided that all pages will only have page name and a component that will have page content.

@page "/"<PageTitle>Home</PageTitle><Sindikat.Web.Client.Components.Home></Sindikat.Web.Client.Components.Home>

Routes.razor:

@using Microsoft.AspNetCore.Components.WebAssembly.Hosting<Router AppAssembly="typeof(Program).Assembly"><Found Context="routeData">        @if (ShouldRenderRoute(routeData))        {<AuthorizeRouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)"><NotAuthorized><OnNotAuthorized /></NotAuthorized></AuthorizeRouteView><FocusOnNavigate RouteData="routeData" Selector="h1" />        }</Found></Router>    public partial class Routes : ComponentBase    {        private static Assembly clientAssembly;        static Routes()        {            clientAssembly = typeof(Program).Assembly;        }        /// <summary>        /// This disallows rendering of wasm pages on the server.        ///  This solves a problem where we have a wasm component that requires services registered only on client (e.g. HttpClient) which we do not want to have on the server. This happens on navigation to a page that is rendered on wasm, despite Router also being rendered in wasm, server is instantiating the router and router then is trying to instantiate a page and then inject services that are not available on the server.        /// </summary>        /// <param name="routeData"></param>        /// <returns></returns>        private bool ShouldRenderRoute(RouteData routeData)        {            var isWebAssembly = Environment.GetEnvironmentVariable("IsWebAssembly") == "true";            var serverPage = routeData.PageType.Assembly != clientAssembly;            return isWebAssembly || serverPage;        }    }

Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>