解决为MVC和WebAPi添加过滤器
Mvc的就直接在FilterConfig类的RegisterGlobalFilters方法中添加以下代码即可
Web Api的过滤器没有单独一个配置类,可以写在WebApiConfig类的Register中
MVC过滤器
public class MvcHandleErrorAttribute : HandleErrorAttribute { public override void OnException(ExceptionContext filterContext) { //这里可以做错误日志处理或写数据库等操作 Console.WriteLine(filterContext.Exception.Message); base.OnException(filterContext); } }
public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { //filters.Add(new HandleErrorAttribute()); filters.Add(new MvcHandleErrorAttribute()); } }
WebApi过滤器
public class WebApiExceptionFilter : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext context) { var message = context.Exception.Message; if (context.Exception.InnerException != null) message = context.Exception.InnerException.Message; context.Response = new HttpResponseMessage() { Content = new StringContent(message) }; base.OnException(context); } }
public static class WebApiConfig { public static void Register(HttpConfiguration config) { //是为了让WebApi的控制器自动匹配ApiController var suffix = typeof(DefaultHttpControllerSelector).GetField("ControllerSuffix", BindingFlags.Static | BindingFlags.Public); if (suffix != null) suffix.SetValue(null, "ApiController"); //为了让WebApi也支持NameSpace config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(config)); //为WebApi添加过滤器 config.Filters.Add(new WebApiExceptionFilter()); // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } }