blazorblazor-server-side

What is the Proper Way to Configure Blazor Web App Navigation to Handle 404?


I have converted my Blazor Server-side Application to the new Blazor Web App project. Everything works as expected except for when I navigate to a view that does not exist.

I can reproduce what I am experiencing by creating a default Blazor Web App project in Visual Studio, launching via F5, and navigating to /somepaththatdoesnotexist (or any URL that does not exist).

What I experience is a blank white page.

What is the recommended configuration to restore the "not found" experience of the previous Blazor Server-side projects?


Solution

  • For static SSR UseStatusCodePagesWithRedirects has three problems:

    1. it returns 302 result and browser will make another request

    2. the second request returns 200 (but you may want 404)

    3. it will replace browser's URL

    All of them can be fixed with UseStatusCodePagesWithReExecute:

    But keep in mind these middlewares monitor all empty responses with status codes between 400-599. If your only concern is a 404 Not Found page you can also create a catch-all page and it will be used if no other route was matched:

    @page "/{*route}"
    
    <h3>NotFound</h3>
    
    @code {
        [CascadingParameter]
        public required HttpContext HttpContext { get; init; }
    
        [Parameter]
        public required string Route { get; init; }
    
        protected override void OnInitialized()
        {
            HttpContext.Response.StatusCode = 404;
        }
    }