如果 http GetById returns 404,则导航到 NotFound 页面

Navigate to NotFound page if http GetById returns 404

假设我有以下路由模式

有路线

路由器设置如下:

<Router AppAssembly="typeof(Startup).Assembly">
    <Found Context="routeData">
        ....
    </Found>
    <NotFound>
        <p>Sorry, there's nothing at this address.</p>
    </NotFound>
</Router>

我希望页面重定向到 NotFound 页面,如果 http 调用没有找到具有传递给的 ID 的客户URL

现在在我的组件中

protected override async Task OnInitializedAsync()
{
   var customer = await CustomerService.GetById(customerId);
   if (customer == null) 
   {
      // redirect to 404 NOTFOUND         
   }
}

现在看来,URL 中的任何有效整数都会打开 CustomerDetail 组件,当它尝试显示客户详细信息时,它(显然)会崩溃并显示 null reference

我是不是遗漏了什么明显的东西?

编辑: 我试图加载自定义 404 页面并处理我的 http 服务内的导航,但这导致浏览器发生 URL 更改。我想保留错误的 URL 并仍然导航到 404 页面。

您可以使用 NavigationManager

@inject NavigationManager _nagigationManager;
...
@code {
    protected override async Task OnInitializedAsync()
    {
       var customer = await CustomerService.GetById(customerId);
       if (customer == null) 
       {
          _navigationManager.NavigateTo("404page");
       }
   }
}

如果您想停留在同一页面上,但显示错误页面的内容,只需在 html 代码中添加该组件即可:

@if(_notFound) 
{
    <NotFoundPage />
}
else
{
...
}
@code {
    private bool _notFound;
    protected override async Task OnInitializedAsync()
    {
       var customer = await CustomerService.GetById(customerId);
       if (customer == null) 
       {
          _notFound = true;
          StateHasChanged();
       }
   }
}