【发布时间】:2022-07-01 16:45:03
【问题描述】:
我正在尝试在我的 ASP.Net Core 5.0 项目中使用中间件进行异常处理,但它不处理异常,并且在抛出异常时调试会停止应用程序。
public class CustomExceptionMiddleWare
{
private readonly RequestDelegate _next;
public CustomExceptionMiddleWare(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
var watch = Stopwatch.StartNew();
try
{
string message = "[Request] HTTP " + context.Request.Method + " - " + context.Request.Path;
Console.WriteLine(message);
await _next(context);
watch.Stop();
message = "[Request] HTTP " + context.Request.Method + " - " + context.Request.Path + " responded " +
context.Response.StatusCode.ToString() + " in " + watch.Elapsed.TotalMilliseconds + " ms";
Console.WriteLine(message);
}
catch (Exception ex)
{
watch.Stop();
await HandleException(context, ex, watch);
}
}
private Task HandleException(HttpContext context, Exception ex, Stopwatch watch)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
string message = "[Error] HTTP" + context.Request.Method + " - " + context.Response.StatusCode +
" Error Message " + ex.Message + " in " + watch.Elapsed.TotalMilliseconds + " ms";
Console.WriteLine(message);
var result = JsonConvert.SerializeObject(new { Error = ex.Message }, Formatting.None);
return context.Response.WriteAsync(result);
}
}
public static class CustomExceptionMiddlewareExtension
{
public static IApplicationBuilder UseCustomExceptionMiddleWare(this IApplicationBuilder builder)
{
return builder.UseMiddleware<CustomExceptionMiddleWare>();
}
}
}
startup.cs:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
//app.UseDeveloperExceptionPage();
app.UseCustomExceptionMiddleWare();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "PatikaWebApi v1"));
}
//app.UseMiddleware<CustomExceptionMiddleWare>();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseCustomExceptionMiddleWare();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
控制器
[HttpGet("{id}")]
public IActionResult GetById(int id)
{
BookDetailViewModel result;
GetBooksDetailQuery query = new GetBooksDetailQuery(_context,_mapper);
query.BookId = id;
GetBooksDetailQueryValidator validator = new GetBooksDetailQueryValidator();
validator.ValidateAndThrow(query);
result = query.Handle();
return Ok(result);
}
当抛出异常时,中间件不使用调试模式处理异常。我搜索了解决方案,发现删除 app.UseDeveloperExceptionPage(); 行对我不起作用。我尝试更改管道但也没有工作。解决方案是什么?感谢您的关注。
错误是用户未处理的异常
【问题讨论】:
标签: c# exception middleware .net-5