MVC-过滤器
过滤器有4种
类别 | 实现接口 | 默认类实现 | 说明 |
Authorization |
IAuthorizationFilter |
AuthorizeAttribute |
在所有的Action之前以及所有的过滤器运行之前执行,实现权限验证 |
Action |
IActionFilter |
ActionFilterAttribute | 在Action将要执行和执行后运行,但是在Result之前 |
Result |
IResultFilter |
ActionFilterAttribute | 在将要返回Result之前和之后运行 |
Exception |
IExceptionFilter |
HandleErrorAttribute |
在执行Filter和Action过程中出现异常时运行,可用于异常处理 |
因为Controller类也实现了上面的4个接口 IActionFilter, IAuthorizationFilter, IExceptionFilter, IResultFilter,因此在Controller类中,也可以实现对应的方法。执行顺序如下:
[MyAuthorizationFilter] [MyActionFilter] public class IndexController : Controller { public ActionResult Index() { Response.Write("我是IndexController中的Index<hr />"); return View(); } protected override void OnAuthorization(AuthorizationContext filterContext) { filterContext.HttpContext.Response.Write("我是IndexController中的OnAuthorization<hr />"); base.OnAuthorization(filterContext); } protected override void OnActionExecuting(ActionExecutingContext filterContext) { filterContext.HttpContext.Response.Write("我是IndexController中的OnActionExecuting<hr />"); base.OnActionExecuting(filterContext); } protected override void OnActionExecuted(ActionExecutedContext filterContext) { filterContext.HttpContext.Response.Write("我是IndexController中的OnActionExecuted<hr />"); base.OnActionExecuted(filterContext); } protected override void OnResultExecuting(ResultExecutingContext filterContext) { filterContext.HttpContext.Response.Write("我是IndexController中的OnResultExecuting<hr />"); base.OnResultExecuting(filterContext); } protected override void OnResultExecuted(ResultExecutedContext filterContext) { filterContext.HttpContext.Response.Write("我是IndexController中的OnActionExecuted<hr />"); base.OnResultExecuted(filterContext); } }
public class MyActionFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { filterContext.HttpContext.Response.Write("我是MyActionFilter中的OnActionExecuting<hr />"); base.OnActionExecuting(filterContext); } public override void OnActionExecuted(ActionExecutedContext filterContext) { filterContext.HttpContext.Response.Write("我是MyActionFilter中的OnActionExecuted<hr />"); base.OnActionExecuted(filterContext); } public override void OnResultExecuting(ResultExecutingContext filterContext) { filterContext.HttpContext.Response.Write("我是MyActionFilter中的OnResultExecuting<hr />"); base.OnResultExecuting(filterContext); } public override void OnResultExecuted(ResultExecutedContext filterContext) { filterContext.HttpContext.Response.Write("我是MyActionFilter中的OnResultExecuted<hr />"); base.OnResultExecuted(filterContext); } }
public class MyAuthorizationFilter:AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { filterContext.HttpContext.Response.Write("我是MyAuthorizationFilter中的OnAuthorization<hr />"); return; } }
全局Controller配置,在Controller级中添加,对应的Action放在对应的Action级中添加。如果是整个项目注册,是在App_Start中FilterConfig中配置。