zoukankan      html  css  js  c++  java
  • .NetCore 3.1 全局异常捕获 API

     创建自定义的中间件来实现我们的自定义异常处理

    1 、CustomExceptionMiddleware

     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

     //全局异常日志
     app.UseMiddleware<CustomExceptionMiddleware>();
    

    第二种

    .NET Core 给我们提供了一种处理全局异常的方式,只需要稍加修改,就可以使用内置且完善的的中间件。我们需要做的修改就是在 Startup 类中修改 Configure方法:

    // 全局异常捕获
                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

    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} 
     " +
                                      $"Method:{method} 
     " +
                                      $"ActionArguments:{actionArguments}
     " +
                                      $"Response:{response}
     ");
            }
        }
    

    2、Startup ConfigureServices

    services.AddMvc(options =>
        {
            options.Filters.Add(typeof(ApiLogFilter));
        });
    

      

    转载记录:https://www.cnblogs.com/xiangxiufei/p/13337926.html

      

  • 相关阅读:
    非域,非匿名用户访问远程企业服务的详细步骤
    调用远程的企业服务的安全问题
    未能加载文件或程序集“****”或它的某一个依赖项的一种情况
    XAMPP使用非80端口的安装配置修改
    Lucene 的存储结构概述
    .NET Framework 4.0 SDK的安装
    lucene 文件存储相关的几个类
    ASP.NET 状态服务 及 session丢失问题解决方案总结
    不安装.net framework框架运行.Net 程序的方法<收藏>
    net面试题集及答案
  • 原文地址:https://www.cnblogs.com/shenghuotaiai/p/13613536.html
Copyright © 2011-2022 走看看