【问题标题】:Navigate to NotFound page if http GetById returns 404如果 http GetById 返回 404,则导航到 NotFound 页面
【发布时间】:2023-04-08 08:19:01
【问题描述】:

假设我有以下路由模式

  • CustomerListComponent:包含客户列表
  • CustomerDetailComponent:保存特定客户的详细信息

有路线

  • @page“客户”

  • @page "customer/{id:int}

和这样的路由器设置:

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

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

现在在我的组件中

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 页面。

【问题讨论】:

    标签: blazor blazor-client-side


    【解决方案1】:

    您可以使用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();
           }
       }
    }
    

    【讨论】:

    • 这是否保留了在浏览器上引发 404 的错误 url?我想通过将 url 更改为“.../my-not-found-page/”来避免丢失信息
    • 你可以在查询字符串中找到错误的url
    • 我会投票,但这会导致奇怪的行为。例如,如果我的@page 有一个 int 限制,例如 path "customer/{id: int} 这将通过此代码查找错误的 Id,但如果传递的 Id 大于,它将通过标准未找到部分一个 int32。我宁愿在一个地方处理它,而不是两个不同的地方。
    • @IoannisStefanou 在 WASM 或服务器上?
    猜你喜欢
    • 2011-04-24
    • 2013-08-28
    • 2017-10-29
    • 1970-01-01
    • 2020-05-12
    • 2017-10-26
    • 2021-06-13
    • 1970-01-01
    • 2018-06-26
    相关资源
    最近更新 更多