如何处理 ASP.net Core C# 中间件中的错误?
创建一个名为 CustomExceptionMiddleware 的新文件夹,并在其中创建一个 ExceptionMiddleware.cs 类。
我们首先要通过依赖注入来注册我们的 IloggerManager 服务和 RequestDelegate。
RequestDeleagate 类型的 _next 参数是一个函数委托,可处理我们的 HTTP 请求。
在完成注册过程后,我们需要创建 InvokeAsync() 方法。如果没有它,RequestDelegate 无法处理请求。
_next 委托应处理请求,并且从我们的控制器获得的 Get 操作应产生成功的响应。但是,如果请求不成功(是的,因为我们强制引发了异常),
我们的中间件将触发 catch 块并调用 HandleExceptionAsync 方法。
public class ExceptionMiddleware{
private readonly RequestDelegate _next;
private readonly ILoggerManager _logger;
public ExceptionMiddleware(RequestDelegate next, ILoggerManager logger){
_logger = logger;
_next = next;
}
public async Task InvokeAsync(HttpContext httpContext){
try{
await _next(httpContext);
}
catch (Exception ex){
_logger.LogError($"Something went wrong: {ex}");
await HandleExceptionAsync(httpContext, ex);
}
}
private Task HandleExceptionAsync(HttpContext context, Exception exception){
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return context.Response.WriteAsync(new ErrorDetails(){
StatusCode = context.Response.StatusCode,
Message = "Internal Server Error from the custom middleware."
}.ToString());
}
}为我们的 ExceptionMiddlewareExtensions 类添加另一个静态方法 -
public static void ConfigureCustomExceptionMiddleware(this IApplicationBuilder
app){
app.UseMiddleware<ExceptionMiddleware>();
}在 Startup 类中的 Configure 方法中使用此方法 -
app.ConfigureCustomExceptionMiddleware();
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP