在Blazor应用中,如果用户访问的页面不存在或者发生路由匹配异常,Blazor框架会抛出未处理的异常。为了避免这种情况的发生,我们可以在Blazor应用中添加一个Catch-all路由,来处理所有未匹配到的页面请求。
下面是一个针对Blazor WebAssembly应用的Catch-all路由示例:
1、在App.razor文件中引用路由配置:
@using Microsoft.AspNetCore.Components.Routing
然后在Router元素中添加NotFound组件路径:
Sorry, there's nothing at this address.
2、 在Startup.cs文件中添加路由捕获:
app.UseBlazorFrameworkFiles(); app.UseStaticFiles();
app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapFallbackToFile("index.html");
endpoints.MapFallbackToPage("/_Host");
endpoints.MapFallbackToPage("/{**slug}", "/NotFound");
});
这样,在Blazor应用中添加Catch-all路由之后,就能够正确地处理所有未匹配到的页面请求,并且避免未处理的异常的发生。