ASP.NET Web API全局异常过滤器

  /// 
    /// 全局异常过滤器 
    /// 
    /// 20210910 
    public class GlobalExceptionFilter : IExceptionFilter
    {
        public bool AllowMultiple => true;

        public Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext,
            CancellationToken cancellationToken)
        {
            return Task.Run(() =>
            {
                
                var errormsg = actionExecutedContext.Exception.GetOriginalException();

                //异常记录日志到本地 
                Logs.LogWriter(errormsg);

                HttpResponseMessage httpResponse = new HttpResponseMessage();

                HttpContent httpContent = new StringContent(errormsg);

                httpResponse.Content = httpContent;

                actionExecutedContext.Response = httpResponse;

            });
        }
    }

在Global.asax启动配置全局过滤器

GlobalConfiguration.Configuration.Filters.Add(new GlobalExceptionFilter());

你可能感兴趣的:(asp.net,全局过滤器)