.NetCore 3.1 全局异常捕获 API
创建自定义的中间件来实现我们的自定义异常处理
1 、CustomExceptionMiddleware
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | public class CustomExceptionMiddleware { private readonly RequestDelegate _next; private readonly ILogger<CustomExceptionMiddleware> _logger; public CustomExceptionMiddleware(RequestDelegate next, ILogger<CustomExceptionMiddleware> logger) { _next = next; _logger = logger; } public async Task Invoke(HttpContext context) { try { await _next(context); } catch (Exception e) { await ExceptionHandlerAsync(context, e); } } private async Task ExceptionHandlerAsync(HttpContext context, Exception ex) { context.Response.ContentType = "application/json" ; context.Response.StatusCode = StatusCodes.Status200OK; _logger.LogError($ "系统出现错误:{ex.Message}--{ex.StackTrace}" ); var result = new ResultObject(500, ex.Message); await context.Response.WriteAsync(JsonConvert.SerializeObject(result)); } } // Extension method used to add the middleware to the HTTP request pipeline. public static class CustomExceptionMiddlewareExtensions { public static IApplicationBuilder UseCustomExceptionMiddleware( this IApplicationBuilder builder) { return builder.UseMiddleware<CustomExceptionMiddleware>(); } } |
2、Configure
1 2 | //全局异常日志 app.UseMiddleware<CustomExceptionMiddleware>(); |
第二种
.NET Core 给我们提供了一种处理全局异常的方式,只需要稍加修改,就可以使用内置且完善的的中间件。我们需要做的修改就是在 Startup
类中修改 Configure
方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | // 全局异常捕获 app.UseExceptionHandler(errors => { errors.Run(async context => { var feature = context.Features.Get<IExceptionHandlerPathFeature>(); var error = feature?.Error; var result = new ResultObject(500, error.Message); if (error != null ) { _logger.LogError($ "系统出现错误:{error.Message}-{error.StackTrace}" ); } context.Response.StatusCode = StatusCodes.Status200OK; context.Response.ContentType = "application/json" ; await context.Response.WriteAsync(JsonConvert.SerializeObject(result)); }); }); |
API请求日志记录
1、ApiLogFilter
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public class ApiLogFilter : IAsyncActionFilter { private readonly ILogger logger; public ApiLogFilter(ILogger<ApiLogFilter> logger) { this .logger = logger; } public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { string actionArguments = context.ActionArguments.ToJson(); var resultContext = await next(); string url = resultContext.HttpContext.Request.Host + resultContext.HttpContext.Request.Path + resultContext.HttpContext.Request.QueryString; string method = resultContext.HttpContext.Request.Method; dynamic result = resultContext.Result.GetType().Name == "EmptyResult" ? new { Value = "EmptyResult" } : resultContext.Result as dynamic; string response = JsonConvert.SerializeObject(result.Value); logger.LogInformation($ "URL:{url} \n " + $ "Method:{method} \n " + $ "ActionArguments:{actionArguments}\n " + $ "Response:{response}\n " ); } } |
2、Startup ConfigureServices
1 2 3 4 | services.AddMvc(options => { options.Filters.Add( typeof (ApiLogFilter)); }); |
转载记录:https://www.cnblogs.com/xiangxiufei/p/13337926.html
分类:
.NET CORE
标签:
API 日志 全局异常 过滤器
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)