app.UseExceptionHandler("/Error");
app.UseStatusCodePagesWithReExecute("/Error/{0}");
app.Use(async (context, next) =>
{
try
{
await next();
}
catch (Exception ex)
{
context.Response.StatusCode = 500;
await context.Response.WriteAsync(ex.Message);
}
});
检查代码中是否有未处理的异常。如果代码或 Razor 页面中出现未处理的异常,Blazor 服务端将无法调用 UseExceptionHandler 方法。
若要自定义错误处理程序并在 UseExceptionHandler 方法中使用它,则需要将代码编写在正确的位置。例如,如果您要自定义错误处理程序并处理 404 错误,则需要如下编写代码:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//...
app.UseExceptionHandler(builder =>
{
builder.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
context.Response.ContentType = "text/html";
await context.Response.WriteAsync("您请求的页面不存在");
});
});
//...
}
检查依赖项是否正确引用,是否存在版本冲突等问题。
如果问题仍然存在,可以尝试在 Visual Studio 中清理解决方案并重新生成项目。