如何在中间件 C# Asp.net Core 中处理错误?
csharpserver side programmingprogramming更新于 2025/4/14 21:52:17
创建一个名为 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();
相关文章
打印
下一节:C# Asp.net Core 中的 AddSingleton、AddScoped 和 Add Transient 分别是什么? ❯❮ 上一节:C# Asp.net Core 中的元包是什么?

