我的ASP.NET Core应用程序中具有以下中间件:
public class ExceptionHandlingMiddleware : IMiddleware
{
// Constructor and other stuff...
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
try
{
await next(context);
}
catch (Exception ex)
{
_logger.Error(ex, "An unhandled exception was thrown!");
await HandleExceptionAsync(context, ex);
}
}
private async Task HandleExceptionAsync(HttpContext context, Exception ex)
{
// Handle exception and return a human-readable
// message in a JSON-object in the response...
}
}
我在Startup.cs中添加到管道
app.UseMiddleware<ExceptionHandlingMiddleware>();
从Visual Studio运行应用程序时,调试器不会在发生异常时中断,而只是在中间件中进行处理并继续执行。但是,我希望调试器在该中间件没有被其他任何东西捕获时,在引发异常的地方中断。 我该如何实现?
我实际上尝试在本地运行时不添加此中间件。例如。在Startup.cs中执行以下操作:
// I'm setting env to "none" when running locally
if (!env.IsEnvironment("none"))
{
app.UseMiddleware<ExceptionHandlingMiddleware>();
}
但是,这似乎只会导致前端的行为有所不同-可以理解,因为它没有接收到可读的JSON对象,但这使我认为问题不在于我的中间件。我宁愿保持此中间件处于活动状态,但是如果在使调试器正常运行时无法这样做,我想我可以接受。