Create an exception handler class ExceptionAPIFilter, implement interfaces inherit 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; }); } }
Sign exception filter OK in the Global.asax
// API global exception filter GlobalConfiguration.Configuration.Filters.Add(new ExceptionAPIFilter());