.Net 8 Blazor Web App 如何将不存在的 url 映射到 <NotFound> 元素

问题描述 投票:0回答:1

这是一个交互式 WebAssembly Blazor Web 应用程序。

当用户单击不存在的网址的链接时,我希望应用程序进入

<NotFound>
中的
<Router>
元素设置:

链接如下:

<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>

路由器是这样的:

<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>

服务器端

Program.cs
是这样的:

 builder.Services.AddRazorComponents()
     .AddInteractiveWebAssemblyComponents();

 ...

 app.MapRazorComponents<App>()
     .AddInteractiveWebAssemblyRenderMode()
     .AddAdditionalAssemblies(typeof(Client._Imports).Assembly);

现在的问题是,当点击这样的链接时,应用程序只是刷新,然后浏览器转到默认的404未找到。

我喜欢通过应用程序来处理这个问题,我该如何实现?

.net asp.net-core razor blazor
1个回答
0
投票

这是一个常见问题,有解决方案。

让程序中的 UseStatusCodePagesWithRedirects 来处理它。

app.UseStatusCodePagesWithRedirects("/not-found")
app.run();

对此有相同的讨论https://github.com/dotnet/aspnetcore/issues/48983

© www.soinside.com 2019 - 2024. All rights reserved.