Asp.Net 5/核心 app.UseExceptionHandler() 不工作

Asp.Net 5/Core app.UseExceptionHandler() not working

我在启动

(更新:解决方案是将 UseRouting 移动到 /api/error 路由下)

app.UseRouting();

if (env.IsDevelopment()) {               
    app.UseExceptionHandler("/api/error/error-local-development"); 
    SwaggerConfig.Configure(app);              
}
else {             
    app.UseExceptionHandler("/api/error/error");
}

 app.UseCors();
 app.UseHttpsRedirection();
 app.UseDefaultFiles();
 app.UseSpaStaticFiles(); 
 app.UseAuthentication();
 app.UseAuthorization();
 app.UseRequestLocalization(options);
  app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<ResultHub>("/hubs/resultHub");
            });


            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "wwwroot";
            });

但是当 throw new Exception() 在控制器操作中时,永远不会调用错误控制器方法。

[Route("api/error")]
[ApiController]
[ApiExplorerSettings(IgnoreApi = true)]
public class ErrorController : OwnBaseController
{
    public ErrorController(IApplicationUserService applicationUserService, ILogger<ErrorController> logger, IDiagnosticContext diagnosticContext) : base(applicationUserService, logger, diagnosticContext)
    {
    }

    [Route("error")]
    public IActionResult Error()
    {
        return Problem(); 
    }

    [Route("error-local-development")]
    public IActionResult ErrorLocalDevelopment([FromServices] IWebHostEnvironment webHostEnvironment)
    {
       var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
       return Problem(
            detail: context.Error.StackTrace,
            title: context.Error.Message);
    }
}

这可能看起来很奇怪,但顺序很重要。

UseExceptionHandlerUseRouting 都在后台注册中间件。

首先注册的是最外层的中间件。因此,如果内部抛出异常,外部可以捕获它并可以处理(and/or 记录)它。

Source

MSDN 对此有一些警告,例如:

If an endpoint within the app is specified, create an MVC view or Razor page for the endpoint. Ensure UseStatusCodePagesWithReExecute is placed before UseRouting so the request can be rerouted to the status page.

UseExceptionHandler is the first middleware component added to the pipeline. Therefore, the Exception Handler Middleware catches any exceptions that occur in later calls.