创建一个异常处理类ExceptionAPIFilter,继承 IExceptionFilter 实现接口
public class ExceptionAPIFilter : IExceptionFilter { public bool AllowMultiple => true; public Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken) { var ex = actionExecutedContext.Exception.InnerException ?? actionExecutedContext.Exception; return Task.Run(() => { string controllerName = actionExecutedContext.ActionContext.ControllerContext.ControllerDescriptor.ControllerName; string actionName = actionExecutedContext.ActionContext.ActionDescriptor.ActionName; string param = actionExecutedContext.Request.Method.ToString(); //记录日志 LogFile.WriteErrorLog(DateTime.Now + string.Format(" Location:{0}/{1} Param:{2} UserIP:{3} Exception:{4}", controllerName, actionName, param, "", ex.Message)); ResultU result = new ResultU(false, 999, ex.Message); string json = Newtonsoft.Json.JsonConvert.SerializeObject(result); HttpResponseMessage httpResponse = new HttpResponseMessage(); HttpContent httpContent = new StringContent(json); httpResponse.Content = httpContent; actionExecutedContext.Response = httpResponse; }); } }
在 Global.asax 中注册 异常过滤器 OK
// API 全局异常过滤 GlobalConfiguration.Configuration.Filters.Add(new ExceptionAPIFilter());