Search code examples
c#asp.net-corevisual-studio-2022blazor-webassembly.net-8.0

How do I provide the missing 404 handling for Visual Studio's Blazor Web App?


I am mainly using Interactive render mode: WebAssembly and Interactivity location: Global, but the issue exists with each template setting. Can someone give me an indication of what I need to do to implement a simple 404 page?

Update: I was told to add app.UseStatusCodePagesWithReExecute( "/StatusCode/{0}" ); to my Program.cs (in this case, the server-side one), and then add a page StatusCode.razor (in this case, on the client) to output the status code:

@page "/StatusCode/{ResponseCode}"

@inherits MainLayout;

<p>@this.ResponseCode</p>

@code {
    [Parameter]
    public string? ResponseCode { get; set; }
}

This seems to work, but then a moment later it gets replaced with a blank page displaying only Not found. I assume this is due to some middleware or other, but I have further idea at the moment.


Solution

  • There is an easy way to do through MapFallback.

    server-side Program.cs

    var builder = WebApplication.CreateBuilder(args);
    
    builder.Services.AddControllersWithViews();
    builder.Services.AddRazorPages();
    
    // Add services to the container.
    builder.Services.AddRazorComponents()
        .AddInteractiveWebAssemblyComponents();
    
    var app = builder.Build();
    
    ...
    
    app.MapRazorComponents<App>()
        .AddInteractiveWebAssemblyRenderMode()
        .AddAdditionalAssemblies(typeof(BlazorApp1.Client._Imports).Assembly);
    
    app.MapRazorPages();
    app.MapControllers();
    app.MapFallbackToFile("404page.html");
    
    app.Run();
    

    client-side wwwroot/404page.html

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <h1>Sorry, we couldn't find the page you're looking for</h1>
    </body>
    </html>
    

    enter image description here