[Solved] <Router> is not working as expected in Blazor 8 – Blazor

by
Ali Hasan
asp.net-core-8 blazor blazor-server-side blazor-webassembly

The Problem:

&lt;Router&gt; component in Blazor 8 Interactive Web Assembly is not functioning as expected. When navigating to unauthorized routes, a 401 error is encountered instead of displaying the dedicated &lt;NotAuthorized&gt; section. Additionally, accessing incorrect URLs doesn’t trigger the &lt;NotFound&gt; section. This issue arises when migrating a working Blazor 7 WASM app to Blazor 8 Interactive Web Assembly, specifically in the Server project’s Routes.razor component. The &lt;Router&gt; configuration remains the same, but it fails to behave as intended in Blazor 8.

The Solutions:

Solution 1: Handle 404 errors gracefully

In Blazor 8, custom 404 error pages are no longer supported. Instead, you can use the `UseStatusCodePagesWithReExecute` middleware to handle 404 errors gracefully. Add the following line to your `Startup.cs` file:

app.UseStatusCodePagesWithReExecute("/StatusCode/{0}");

This will create a new route that will handle 404 errors and redirect the user to a custom error page. You can then create a new Razor page for your error page, such as Pages/StatusCode.razor. The following code shows an example of a custom 404 error page:

@page "/StatusCode/{statusCode}"

<h1>Error {statusCode}</h1>

<p>Sorry, but we couldn't find the page you were looking for.</p>

<a href="/">Return to the home page</a>

With this change, Blazor 8 will use the custom error page to handle 404 errors, providing a better user experience.

Solution 2: Update `Program.cs` and create a new Razor component for the 404 error page.

Here’s a more detailed explanation of the steps to fix the issue with the `<Router>` component in Blazor 8:

1. Update Program.cs:

  • In the Program.cs file, add the following line to configure the status code pages:
app.UseStatusCodePagesWithReExecute("/StatusCode/{0}");

This line tells the application to use the StatusCodePagesWithReExecute middleware to handle status code errors. It will automatically redirect the user to a specific page for each status code, such as "/StatusCode/404" for a 404 error.

2. Create a Razor component for the 404 error page:

  • Navigate to the Components/Pages folder and create a new Razor component.

  • Give it a suitable name, such as NotFound.razor.

  • In the NotFound.razor file, add the following code:

@page "/StatusCode/404"

<PageTitle>Not Found</PageTitle>

<h3>Not Found</h3>

<p role="alert">Sorry, there's nothing at this address.</p>

@code { }

This Razor component will serve as the 404 error page for your application.

By following these steps, you can fix the issue with the &lt;Router&gt; component and ensure that the 404 error page is displayed correctly in Blazor 8.

Solution 3: The problem was in the `App.razor` file and the `<Router>` tag.

In Blazor 8, the `<Router>` tag should be placed inside the `<CascadingAuthenticationState>` component to ensure that authentication-related state is properly cascaded to child components.

Here is the corrected code for `App.razor`:

&lt;CascadingAuthenticationState&gt;
    &lt;Router AppAssembly=&quot;@typeof(Program).Assembly&quot;&gt;
        &lt;Found Context=&quot;routeData&quot;&gt;
            &lt;AuthorizeRouteView RouteData=&quot;@routeData&quot; DefaultLayout=&quot;@typeof(MainLayout)&quot;&gt;
                &lt;NotAuthorized&gt;
                    &lt;h2&gt;You are not authorized.&lt;/h2&gt;
                    &lt;h3&gt;To log in click &lt;a href=&quot;/Accounts/LogIn&quot;&gt;here&lt;/a&gt;.&lt;/h3&gt;
                &lt;/NotAuthorized&gt;
            &lt;/AuthorizeRouteView&gt;
        &lt;/Found&gt;
        &lt;NotFound&gt;
            &lt;CascadingAuthenticationState&gt;
                &lt;LayoutView Layout=&quot;@typeof(MainLayout)&quot;&gt;
                    &lt;p&gt;Sorry, there&#39;s nothing at this address.&lt;/p&gt;
                &lt;/LayoutView&gt;
            &lt;/CascadingAuthenticationState&gt;
        &lt;/NotFound&gt;
    &lt;/Router&gt;
&lt;/CascadingAuthenticationState&gt;

This change ensures that the `<AuthorizeRouteView>` and `<NotFound>` components have access to the current authentication state, allowing them to display the appropriate content based on the user’s authorization status.

Video Explanation:

The following video, titled "Meet the YouTuber Who Solved Shorts (Jenny Hoyos Interview ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

GET MY FREE COURSE Professional Creator Crash Course: https://creatorscience.co/course SPONSOR - USCREEN Create your own video membership ...