先看一段实例
public class Log : FilterAttribute, IActionFilter { public void OnActionExecuted(ActionExecutedContext filterContext) { Console.WriteLine("log-after"); } public void OnActionExecuting(ActionExecutingContext filterContext) { Console.WriteLine("log-before"); } }
public class HomeController : Contoller { [Log] public ActionResult Index() { return View(); } }
MVC有四种过滤器
ActionFilter(方法过滤器):实现接口:[IActionFilter];在Action调用前和调用后执行
ResultFilter(结果过滤器):实现接口:[IResultFilter];在Action Result调用完,跳转至view页面前/后执行
AuthorizationFilter(授权过滤器):实现接口:[IauthorizationFilter];所有过滤器中最先执行的
ExceptionFilter(异常处理过滤器):实现接口:[IExceptionFilter]:在控制器方法抛出异常时执行
应用场景
public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); filters.Add(new MyAuthorAttribute()); filters.Add(new ExceptionFilter());//异常过滤器 } }
public class MyAuthorAttribute : FilterAttribute, IAuthorizationFilter { public void OnAuthorization(AuthorizationContext filterContext) { /// } }
Global实现全局
//实现全局 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);