Asp.net-Core

Blazor:實現 404 未找到頁面

  • December 6, 2021

我想在我的應用程序內部實現一個頁面,當 blazor 路由器無法找到匹配的路由時出現該頁面。目前,所有請求都被路由到,index.html所以我無法像往常一樣通過 iis 處理錯誤。如果我輸入了一個無效的路由,我將看到一個空白頁面(實際上是index.html)並收到一個控制台錯誤:

'Router' cannot find any component with a route for '/some/Nonexistent/Route'.

看起來我應該能夠處理這個問題,因為 blazor 路由器能夠辨識出沒有定義的路由與請求的路由匹配,但是到目前為止我還沒有找到任何關於此的文件。

我該如何實施?有沒有辦法連接到 blazor 路由器並將所有未找到的路由定向到預定義的錯誤路由?

我看到https://github.com/aspnet/AspNetCore/issues/5489列出了一個 404 處理程序的問題,但是我不確定這是否比我想要的更強大和生產就緒

試試這個:App.cshtml

<Router AppAssembly=typeof(Program).Assembly FallbackComponent="typeof(Error404)" >

創建一個名為 Error404.cshtml 的組件

注意:這只是我從探勘 Router 類中收集的一個猜測。請參閱https://github.com/aspnet/AspNetCore/blob/343208331d9ebbb3a67880133f4139bee2cb1c71/src/Components/src/Microsoft.AspNetCore.Components/Routing/Router.cs

請讓我知道它是否適合您。

在下App.razor添加<NotFound>元素<Router>,設置當 Blazor 找不到指定路由時要顯示的內容。

例如:

<Router AppAssembly="typeof(Program).Assembly">
   <NotFound>
       <h1>404 Not Found</h1>
   </NotFound>
</Router>

(注意:如果它是伺服器端應用程序,那麼它將是typeof(Startup).Assembly

資源

引用自:https://stackoverflow.com/questions/53859078