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

ede*_*ter 13 c# error-handling asp.net-core asp.net5

我在启动时有

(更新:解决方案是将 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";
            });

Run Code Online (Sandbox Code Playgroud)

但是,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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*ala 15

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

UseExceptionHandler并且UseRouting都在后台注册中间件。

最先注册的将是最外层的中间件。因此,如果内部之一抛出异常,外部可以捕获并处理它。

中间件排序 来源

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

如果指定了应用程序内的端点,请为端点创建 MVC 视图或 Razor 页面。确保UseStatusCodePagesWithReExecute放置在之前UseRouting,以便可以将请求重新路由到状态页面。

UseExceptionHandler是添加到管道中的第一个中间件组件。因此,异常处理程序中间件会捕获后续调用中发生的任何异常。

  • 嗨@PeterCsala,我在准备在这里发布详细信息时发现了我的问题。我在开发模式下运行,对“app.UseExceptionHandler()”的调用仅在“IsDevelopmentMode = false”时有效。愚蠢的错误。现在一切都很完美。 (2认同)