如何处理中间件 C# Asp.net Core 中的错误?
创建一个名为 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();
}
登录后复制
在 Startup 类的配置方法中使用此方法 –
app.ConfigureCustomExceptionMiddleware();
登录后复制
以上就是如何处理中间件 C# Asp.net Core 中的错误?的详细内容,更多请关注恰卡编程网(mip.qiaqa.com)其它相关文章!
推荐阅读
-
Web应用从零开始,初学者友好型开发教程
-
容器化最佳实践:Docker 与 Kubernetes 在微服务架构中的协同设计
-
AWS Cloud9 使用攻略:云端 IDE 如何无缝集成 Lambda 与 S3 服务?
-
Heroku vs AWS Elastic Beanstalk:快速部署 Web 应用的平台对比
-
Kubernetes 集群部署避坑:资源调度、服务发现与滚动更新策略
-
Docker 镜像优化指南:分层构建、瘦身技巧与多阶段编译实践
-
Postman 接口测试全流程:从 API 设计到自动化测试脚本编写
-
pytest 框架进阶:自定义 fixture、插件开发与持续集成集成方案
-
JUnit 5 新特性:参数化测试、扩展模型与微服务测试实践
-
Chrome DevTools 性能分析:FPS 监控、内存快照与网络请求优化指南