This is an Interactive WebAssembly Blazor Web app.
When user click a link which a nonexisting url, I want the app goes the <NotFound>
Element setup in the <Router>
:
The link like this:
<div class="nav-item px-3">
<NavLink class="nav-link px-3" href="not-found">
<span class="bi bi-plus-square-fill-nav-menu" aria-hidden="true"></span> Not Found
</NavLink>
</div>
The router like this:
<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(Layout.MainLayout)" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<div>Not found</div>
</NotFound>
</Router>
The server-side Program.cs
is like this:
builder.Services.AddRazorComponents()
.AddInteractiveWebAssemblyComponents();
...
app.MapRazorComponents<App>()
.AddInteractiveWebAssemblyRenderMode()
.AddAdditionalAssemblies(typeof(Client._Imports).Assembly);
The problem now is, when clicking such a link, the application just refresh, and then browser go to default 404 not found.
I like to handle this by the app, how do I achieve that?
It is a common problem encountered, and there is a solution.
Let the UseStatusCodePagesWithRedirects in your program handle it.
app.UseStatusCodePagesWithRedirects("/not-found")
app.run();
There is a same discussion about this https://github.com/dotnet/aspnetcore/issues/48983