【问题标题】:Return 404 In Blazor Server Page在 Blazor 服务器页面中返回 404
【发布时间】:2022-03-02 19:43:30
【问题描述】:

我正在尝试将 Razor Pages 应用程序迁移到 Blazor Server 应用程序作为分阶段迁移(而不是大爆炸)的一部分。我目前正在移动一组相对直接的 CRUD 页面。这些页面具有典型的路由结构,例如...

/entity/
/entity/edit/{id}
/entity/detail/{id}
/entity/delete/{id}

在“编辑”的剃须刀页面中,我通常会有一个 OnGetAsync 方法,该方法接受 id 作为参数,使用 id 搜索实体并返回页面。但是,如果 id 不是有效实体,我的 OnGet 将返回 NotFound (IActionResult)。我想弄清楚的是如何使用 Blazor 服务器页面/组件来做到这一点。

我的 blazor 页面看起来像这样(只是相关的部分)

@page "/entity/edit/{id:int}"
...
@code {
    [Parameter] public int Id { get; set; }
    public Entity Model { get; set; }
    protected override async Task OnParametersSetAsync()
    {
        Model = await SomeServiceCall.GetAsync(Id);
        if(Model == null)
            return; // TODO: Return 404 rather than the page
    }
}

如何告诉 Blazor 返回 404?这样显示的是我的而不是我的页面?

【问题讨论】:

  • 这个answer 似乎提供了一个解决方案。

标签: asp.net-core blazor razor-pages


【解决方案1】:

你的项目中有 App.razor 文件

<Router AppAssembly="@typeof(App).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        <FocusOnNavigate RouteData="@routeData" Selector="h1" />
    </Found>
    <NotFound>
        <PageTitle>Not found</PageTitle>
        <LayoutView Layout="@typeof(MainLayout)">
            <p role="alert">Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>

查看部分,当 Blazor 找不到正在导航的路径时,它会显示 html 存在此部分,因此您可以将这一行替换为您想要显示的信息

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

【讨论】:

  • 这仅适用于路线不存在的情况。在这种情况下,我需要运行一些代码才能确认路由不存在。例如“/entity/edit/1”是一个真实的实体和一个正确的路由,“/entity/edit/50001”是一个有效的路由,但没有该id的记录,所以页面应该返回“未找到”
  • 能否请您解释一下,您想在哪里返回404,如果找不到您要查找的id,那么您可以有条件地在同一页面中呈现您想要的html
猜你喜欢
  • 2013-08-28
  • 2020-05-12
  • 2020-04-03
  • 1970-01-01
  • 1970-01-01
  • 2017-11-01
  • 2020-03-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多