MVC四大筛选器—ActionFilter&ResultedFilter
AuthorizeFilter筛选器
在Action的执行中包括两个重要的部分,一个是Action方法本身逻辑代码的执行,第二个就是Action方法的筛选器的执行。
MVC4中筛选器都是以AOP(面向方面编程)的方式来设计的,通过对Action方法上标注相应的Attribute标签来实现。MVC4提供了四种筛选器,分别为:AuthorizationFilter、ActionFilter、ExceptionFilter和ResultFilter,他们分别对应了四个筛选器接口IAuthorizationFilter、IActionFilter、IExceptionFilter和IResultFilter。
这四种筛选器都有派生于一个公共的类FilterAttribute,该类指定了筛选器的执行顺序Order和是否允许多个应用AllowedMultiple。这四种筛选器默认的执行顺序为最先进行授权筛选,最后进行异常处理,中间则是ActionFilter和ResultedFilter。
下面是抽象类FilterAttribute的类图

下面我们来具体列举一下各个筛选器的作用和实现
从字面上我们就能看出这是对Controller或Action方法授权的筛选器,即在Controller或Action方法执行前,首先会先执行该筛选器,若通过,才会继续执行。下面是此筛选器的简单类图

AuthorizeAttribute为最终授权筛选器的实现者,它实现了IAuthorizationFilter接口和FilterAttribute抽象类,接口中的OnAuthorization(AuthorizationContext filterContext)方法是最终验证授权的逻辑(其中AuthorizationContext是继承了ControllerContext类)
- protected virtual bool AuthorizeCore(HttpContextBase httpContext)
- {
- if (httpContext == null)
- {
- throw new ArgumentNullException("httpContext");
- }
- IPrincipal user = httpContext.User;
- if (!user.Identity.IsAuthenticated)
- {
- return false;
- }
- if (_usersSplit.Length > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase))
- {
- return false;
- }
- if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole))
- {
- return false;
- }
- return true;
- }
AuthorizeCore方法是最终OnAuthorization()方法调用的最终逻辑,从代码可以看出,当同时指定了users和roles时,两者只有同时满足条件时才可以验证授权通过。如
- [Authorize(Users="zhangsan", Roles="Admin")]
- public ActionResult ActionMethod()
- {
- }
则只有用户zhangsan,且用户属于Admin角色时才能验证授权通过。
若验证不通过时,OnAuthorization方法内部会调用HandleUnauthorizedRequest
虚方法进行处理,代码如下:
- protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext)
- {
- // Returns HTTP 401 - see comment in HttpUnauthorizedResult.cs.
- filterContext.Result = new HttpUnauthorizedResult();
- }
该方法设置了参数上下文中ActionResult的值,用于供View展示。
我们可以自定义Authorize筛选器,由于OnAthurization()、AuthorizeCore()和HandleUnauthorizedRequest()方法都是虚方法,我们自定义的Authorize筛选器只需要继承AuthorizeAttribute类,重写以上三种方法,这样就可以自定义自己的验证规则和验证失败时的处理逻辑了。
IAuthorizationFilter还有其他类型的实现类,如RequireHttpsAttribute、ValidateInputAttribute都是实现了OnAuthorization()方法,来完成各自筛选器处理的。
ExceptionFilter过滤器
该筛选器是在系统出现异常时触发,可以对抛出的异常进行处理。所有的ExceptionFilter筛选器都是实现自IExceptionFilter接口
- public interface IExceptionFilter
- {
- void OnException(ExceptionContext filterContext);
- }
实现OnException方法来实现对异常的自定义处理
MVC4中实现了默认的异常处理机制,源码如下
- public virtual void OnException(ExceptionContext filterContext)
- {
- if (filterContext == null)
- {
- throw new ArgumentNullException("filterContext");
- }
- if (filterContext.IsChildAction)
- {
- return;
- }
- // If custom errors are disabled, we need to let the normal ASP.NET exception handler
- // execute so that the user can see useful debugging information.
- if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
- {
- return;
- }
- Exception exception = filterContext.Exception;
- // If this is not an HTTP 500 (for example, if somebody throws an HTTP 404 from an action method),
- // ignore it.
- if (new HttpException(null, exception).GetHttpCode() != 500)
- {
- return;
- }
- if (!ExceptionType.IsInstanceOfType(exception))
- {
- return;
- }
- string controllerName = (string)filterContext.RouteData.Values["controller"];
- string actionName = (string)filterContext.RouteData.Values["action"];
- HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
- filterContext.Result = new ViewResult
- {
- ViewName = View,
- MasterName = Master,
- ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
- TempData = filterContext.Controller.TempData
- };
- filterContext.ExceptionHandled = true;
- filterContext.HttpContext.Response.Clear();
- filterContext.HttpContext.Response.StatusCode = 500;
- // Certain versions of IIS will sometimes use their own error page when
- // they detect a server error. Setting this property indicates that we
- // want it to try to render ASP.NET MVC's error page instead.
- filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
- }
Application_Start中将HandleErrorAttribute添加到全局筛选器GlobalFilterCollection中,系统即会对异常进行对应的处理。
我们现在实现一个自定义的异常处理筛选器,在处理完后记录异常信息至日志文件中
- public class MyExceptionHandleAttribute : HandleErrorAttribute
- {
- public MyExceptionHandleAttribute()
- : base()
- {
- }
- public void OnException(ExceptionContext filterContext)
- {
- base.OnException(filterContext);
- //记录日志
- log.Info(filterContext.Exception);
- }
- }
在GlobalFilterCollection添加MyExceptionHandleAttribute 即可使用自定义的异常筛选器来处理
ActionFilter筛选器
ActionFilter筛选器是在Action方法执行前后会触发,主要用于在Action执行前后处理一些相应的逻辑。ActionFilter的筛选器都继承于ActionFilterAttribute抽象类,而它实现了IActionFilter、IResultFilter和FilterAttribute类,结构如下

因此自定义ActionFilter筛选器只要继承ActionFilterAttribute,实现其中的方法即可。
我们来举一个简单的例子,获取Action方法的执行时长,代码如下
- public class DefaultController : Controller
- {
- [ActionExecTimeSpan]
- public ActionResult DoWork()
- {
- return View();
- }
- }
- public class ActionExecTimeSpanAttribute : ActionFilterAttribute
- {
- private const string executeActionTimeKey = "ActionExecBegin";
- public override void OnActionExecuting(ActionExecutingContext filterContext)
- {
- base.OnActionExecuting(filterContext);
- //记录开始执行时间
- filterContext.HttpContext.Items[executeActionTimeKey] = DateTime.Now;
- }
- public override void OnActionExecuted(ActionExecutedContext filterContext)
- {
- //计算执行时间,并记录日志
- if (filterContext.HttpContext.Items.Contains(executeActionTimeKey))
- {
- DateTime endTime = DateTime.Now;
- DateTime beginTime = Convert.ToDateTime(filterContext.HttpContext.Items[executeActionTimeKey]);
- TimeSpan span = endTime - beginTime;
- double execTimeSpan = span.TotalMilliseconds;
- log.Info(execTimeSpan + "毫秒");
- }
- //
- base.OnActionExecuted(filterContext);
- }
- }
ResultFilter筛选器
ResultFilter筛选器是对Action方法返回的Result结果进行执行时触发的。它也分执行前和执行后两个段执行
所有的ResultFilter都实现了IResultFilter接口和FilterAttribute类,看一下接口定义
- public interface IResultFilter
- {
- void OnResultExecuting(ResultExecutingContext filterContext);
- void OnResultExecuted(ResultExecutedContext filterContext);
- }
其中OnResultExecuting和OnResultExecuted方法分别是在Result执行前、后(页面展示内容生成前、后)触发。
使用ResultFilter筛选器最典型的应用就是页面静态化,我们以后在其他文章中在对此进行详细讲解
MVC四大筛选器—ActionFilter&ResultedFilter的更多相关文章
- MVC四大筛选器—AuthorizeFilter
在Action的执行中包括两个重要的部分,一个是Action方法本身逻辑代码的执行,第二个就是Action方法的筛选器的执行. MVC4中筛选器都是以AOP(面向方面编程)的方式来设计的,通过对Act ...
- MVC四大筛选器—ExceptionFilter
该筛选器是在系统出现异常时触发,可以对抛出的异常进行处理.所有的ExceptionFilter筛选器都是实现自IExceptionFilter接口 public interface IExceptio ...
- 在ASP.NET MVC中的四大筛选器(Filter)及验证实现
http://www.cnblogs.com/artech/archive/2012/08/06/action-filter.html http://www.cnblogs.com/ghhlyy/ar ...
- MVC常用筛选器Filter
1.ActionFilterAttribute using System; using System.Collections.Generic; using System.Diagnostics; us ...
- mvc 筛选器
之前公司中,运用ActionFilterAttribute特性实现用户登录信息的验证,没事看了看,留下点东西备忘. 好的,瞅这玩意一眼就大概能猜到这货是干嘛的了吧,没错,action过滤器.其实就是A ...
- Asp.Net mvc筛选器中返回信息中断操作
在mvc中,使用response.end()或Response.Redirect("url"); 是无法阻止请求继续往下执行的.如果在action中,可以我们可以使用return ...
- Asp.Net MVC 页面代码压缩筛选器-自定义删除无效内容
Asp.Net MVC 页面代码压缩筛选器 首先定义以下筛选器,用于代码压缩. /*页面压缩 筛选器*/ public class WhiteSpaceFilter : Stream { privat ...
- 基础教程:ASP.NET Core 2.0 MVC筛选器
问题 如何在ASP.NET Core的MVC请求管道之前和之后运行代码. 解 在一个空的项目中,更新 Startup 类以添加MVC的服务和中间件. publicvoid ConfigureServi ...
- 如何在ASP.NET MVC为Action定义筛选器
在ASP.NET MVC中,经常会用到[Required]等特性,在MVC中,同样可以为Action自定义筛选器,来描述控制器所遵守的规则. 首先,我们在ASP.NET MVC项目中定义一个TestC ...
随机推荐
- 网站日志流量分析采集(LuaJIT系统环境部署-node03,相关jar包自己手动上传)
注:/usr/local/src 是源码包路径,可以自己更改 服务器中安装依赖 yum -y install gcc perl pcre-devel openssl openssl-devel 上传 ...
- 【转】nc 使用说明
netcat是网络工具中的瑞士军刀,它能通过TCP和UDP在网络中读写数据.通过与其他工具结合和重定向,你可以在脚本中以多种方式使用它.使用netcat命令所能完成的事情令人惊讶. netcat所做的 ...
- iOS 开发之 KVC - setValuesForKeysWithDictionary 解析
从字典映射到一个对象,这是KVC中的一个方法所提供的,这个方法就是 setValuesForKeysWithDictionary:,非常好用,不需要你来一一的给对象赋值而直接从字典初始化即可,但用的不 ...
- HDMI SCDC处理过程
SCDC State and Control Data Channel 接收端如果有SCDC,应该在E-EDID中包含一个有效的HF-VSDB,并且把SCDC_Present位设置为1.在 ...
- 基于UML的文献管理系统建模研究
一.基本信息 标题:基于UML的文献管理系统建模研究 时间:2016 出版源:信息与电脑(理论版) 领域分类:UML:文献管理系统:系统建模: 二.研究背景 问题定义:图书的管理与规划 难点:系统和管 ...
- SSM_CRUD新手练习(9)显示分页数据
我们已经做好了用来显示数据的分页模板,现在只需要将我们从后台取出的数据填充好,显示出来. 我们使用<c:forEach>标签循环取出数据,所以需要先导入JSTL标签库 <%@ tag ...
- WebRTC 学习之 概念总结
在学习WebRTC的时候,接触到了好多新的概念,在这里做一下备忘吧 RTMP协议 Real Time Messaging Protocol(实时消息传输协议).该协议基于TCP,是一个协议族,包括RT ...
- JSP标准标签库:JSTL
JSTL(JSP Standard Tag Library),JSP标准标签库,可以嵌入在jsp页面中使用标签的形式完成业务逻辑等功能. jstl出现的目的同el一样也是要代替jsp页面中的脚本代码. ...
- 分布式任务调度系统xxl-job相关问题补充
搭建xxl-job时可能会遇到的问题 邮箱配置不起作用报异常 以163邮箱为例,接收邮件需要开启POP3/STMP服务 光开启服务还不够,需要添加授权码 授权码为手动输入,可以与登录密码不同,所以服务 ...
- python中不同文件中函数和类的调用
最近在学习Python的时候,遇到了一个不同文件中类无法调用的问题,搜了很多,发现很多人针对 这个问题都说的相当含糊,让我费了好大劲才把这个东东搞明白.记录一下,权且温习. 调用分两种,一种是同种文件 ...