我正在实现一个 Blazor WebAssembly 托管应用程序,我想在后端项目中使用全局异常处理程序,它会捕获所有未处理的异常,处理它们并最终将问题发送回客户端。
ErrorController 如下所示:
public class ErrorController : ControllerBase
{
private ErrorResponse _errorResponse = null;
[Route("/error")]
public async Task<IActionResult> Error()
{
var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
var exception = context.Error;
var exceptionType = exception.GetType();
if (exceptionType == typeof(CustomException))
{
var customException = (CustomException) exception;
_errorResponse.Message = customException.Message;
_errorResponse.StatusDescription = customException.StatusDescription;
_errorResponse.Status = customException.StatusCode;
}
if (_errorResponse != null)
await SendError();
// Send Problem for fallback
return Problem(exception.Message);
}
private Task SendError()
{
HttpContext.Response.ContentType = "application/json";
HttpContext.Response.StatusCode = _errorResponse.Status;
return HttpContext.Response.WriteAsync(_errorResponse.ToString());
}
控制器在 Startup.Configure 中注册为 ExceptionHandler:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseResponseCompression();
if (env.IsDevelopment())
{
app.UseWebAssemblyDebugging();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
// Does not work
app.UseExceptionHandler("/error");
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapFallbackToFile("index.html");
});
}
尽管我找不到任何提示,Blazor WebAssembly 托管的项目不支持此功能,但当发生未处理的异常时,永远不会调用 ErrorController,只会在应用程序停止时重新抛出异常。
是否澄清了托管的 Blazor WebAssembly 服务器项目中支持哪些中间件?