这里用实例说明各种过滤器的用法,有不对的地方还请大神指出,共同探讨。

1. ActionFilter 方法过滤器:

  接口名为 IActionFilter ,在控制器方法调用前/后执行。

在新建的MVC程序中,添加一个类 MyFilter1Attribute 并继承ActionFilterAttribute抽象类

从上图可以看到 ActionFilterAttribute 中的所有方法,且有相应的介绍,我们可以通过继承 ActionFilterAttribute 类,并重写(override)它的方法,从而实现自定义Filter

   public class MyFilter1Attribute: ActionFilterAttribute
{
/// <summary>
/// 该方法会在Action方法执行之前调用
/// </summary>
/// <param name="filterContext"></param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.HttpContext.Response.Write("我是OnActionExecuting,我在Ation方法调用前执行<br/>");
base.OnActionExecuting(filterContext);
} /// <summary>
/// 该方法会在Action方法执行之后调用
/// </summary>
/// <param name="filterContext"></param>
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
filterContext.HttpContext.Response.Write("我是OnActionExecuted,我在Action方法调用后执行<br/>");
base.OnActionExecuted(filterContext);
} }

然后创建一个HomeController控制器,并添加FilterTest的测试Action

    public class HomeController : Controller
{
public ActionResult Index()
{
return View();
} [MyFilter1]
public void FilterTest()
{
Response.Write("我是Action方法,我在这里执行了.....<br/>");
}
}

运行程序并访问FilterTest方法:

上图可看出它的一个执行顺序

但是有时候也有可能有这样的场景:当检查到Action有标识某个Attribute的时候,我们需要跳出,并不执行后续的方法的情况,我们可以通过filterContextActionDescriptior类中的IsDefained方法进行判断检查

     /// <summary>
/// 该方法会在Action方法执行之前调用
/// </summary>
/// <param name="filterContext"></param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.HttpContext.Response.Write("我是OnActionExecuting,我在Ation方法调用前执行<br/>");
//判断Action方法时是否有贴上MyFilter1Attribute标签
if (filterContext.ActionDescriptor.IsDefined(typeof(MyFilter1Attribute), false))
{
//如果有,为该Action方法直接返回ContentResult,则该Action方法在这里就有了返回值,相当于在这里就结束了,不会再去执行之后的方法,例如:OnActionExecuted
filterContext.Result = new ContentResult();
}
base.OnActionExecuting(filterContext);
}

2.ResultFilter 结果过滤器:

  接口名为 IResultFilter,在控制器方法调用完,跳转至View页面前/后调用

同样在 MyFilter1Attribute 类中重写 OnResultExecuting 方法和  OnResultExecuted 方法

        /// <summary>
/// 该方法在Action方法返回结果之前执行
/// </summary>
/// <param name="filterContext"></param>
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.HttpContext.Response.Write("我是OnResultExecuting,我在Action方法返回结果前执行<br/>");
base.OnResultExecuting(filterContext);
} /// <summary>
/// 该方法在Action方法返回结果之后执行
/// </summary>
/// <param name="filterContext"></param>
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
filterContext.HttpContext.Response.Write("我是OnResultExecuted,我在Action方法返回结果后执行<br/>");
base.OnResultExecuted(filterContext);
}

然后在HomeController控制器中添加 FilterTest1

        [MyFilter1]
public ActionResult FilterTest1()
{
Response.Write("我是测试Action1方法,我在这里执行了.....<br/>");
return View();
}

运行程序,并访问 FilterTest1 ,执行结果如下:

可以看出OnResultExecuting 方法是在返回结果页面之前执行的,而OnResultExecuted是返回结果页面之后执行的

3.ExceptionFilter 异常操作过滤器:

  接口名为 IExceptionFilter,在控制器的Action方法抛出异常时执行

可以通过异常过滤器捕获Controller中发生的异常,并记录到日志。

添加MyExceptionAttribute类,并继承HandleErrorAttribute,如下

        /// <summary>
///
/// </summary>
/// <param name="filterContext"></param>
public override void OnException(ExceptionContext filterContext)
{
filterContext.HttpContext.Response.Write("我是OnException,在Controller中发生异常时进入<br/>"); //获取到异常对象
Exception ex = filterContext.Exception;
//获取请求的Controller和Action
string controllerName = filterContext.RouteData.Values["controller"].ToString();
string actionName = filterContext.RouteData.Values["action"].ToString();
//记录日志
string errMessage = string.Format("异常消息:控制器为:{0},Action为:{1},异常信息为:{2};", controllerName, actionName, ex.Message);
OutPutLog(errMessage); //标记异常已做处理
filterContext.ExceptionHandled = true;
base.OnException(filterContext);
} /// <summary>
/// 输出日志
/// </summary>
/// <param name="message"></param>
public void OutPutLog(string message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "/Logs.txt";
using (StreamWriter sw = new StreamWriter(path, true, Encoding.Default))
{
sw.Flush();
sw.WriteLine("时间:" + DateTime.Now);
sw.WriteLine("内容:" + message);
sw.WriteLine("---------------------------------------------");
}
}

HomeController中添加FilterTest3

 [MyException]
public ActionResult FilterTest3()
{
Response.Write("我是测试Action3方法,我在这里执行了.....<br/>");
string str = "131464ddddd";
int i = int.Parse(str);
return View();
}

运行程序并访问 FilterTest3方法,将会在 str 转换成int类型时抛出异常,随后将进入OnException方法,并记录日志如下:

4.AuthorizationFilter 授权过滤器:

  接口名为 IauthorizationFilter,在所有过滤器中最先执行

添加一个MyFilter2Attribute类,并继承AuthorizeAttribute类,然后重写其OnAuthorization方法:

    public class MyFilter2Attribute: AuthorizeAttribute
{ /// <summary>
/// 在所有的Action方法过滤之前执行
/// </summary>
/// <param name="filterContext"></param>
public override void OnAuthorization(AuthorizationContext filterContext)
{
filterContext.HttpContext.Response.Write("我是OnAuthorization,在所有Action方法过滤器之前执行<br/>");//base.OnAuthorization(filterContext);
}
}

HoneController控制器中添加 FilterTest2

    [MyFilter1]
[MyFilter2]
public ActionResult FilterTest2()
{
Response.Write("我是测试Action2方法,我在这里执行了.....<br/>");
return View();
}

运行程序并访问 FilterTest2  结果如下:

从上图执行结果可以看出,OnAuthorization 权重是最高的,将会在其他所有过滤器之前执行。

注意:

  ActionFilter 和 ResultFilter 不仅可以对单个方法进行操作,也能对整个Controller进行操作,将过滤的头部属性移至控制名称上面即可。

ASP.NET MVC 中的过滤器的更多相关文章

  1. Asp.Net MVC<五>:过滤器

    ControllerActionInvoker在执行过程中除了利用ActionDescriptor完成对目标Action方法本身的执行外,还会执行相关过滤器(Filter).过滤器采用AOP的设计,它 ...

  2. ASP.NET MVC中的错误处理

    ASP.NET MVC中的错误的错误处理跨越了两个主要领域:程序异常和路由异常的处理.前者是关于在控制器和视图中捕获错误的;而后者更多是有关重定向和HTTP错误的. 1.在WebConfig中把过滤器 ...

  3. asp.net MVC之 自定义过滤器(Filter) - shuaixf

    一.系统过滤器使用说明 1.OutputCache过滤器 OutputCache过滤器用于缓存你查询结果,这样可以提高用户体验,也可以减少查询次数.它有以下属性: Duration :缓存的时间, 以 ...

  4. ASP.NET MVC学习之过滤器篇(2)

    下面我们继续之前的ASP.NET MVC学习之过滤器篇(1)进行学习. 3.动作过滤器 顾名思义,这个过滤器就是在动作方法调用前与调用后响应的.我们可以在调用前更改实际调用的动作,也可以在动作调用完成 ...

  5. ASP.NET MVC学习之过滤器篇(1)

    一.前言 继前面四篇ASP.NET MVC的随笔,我们继续向下学习.上一节我们学习了关于控制器的使用,本节我们将要学习如何使用过滤器控制用户访问页面. 二.正文 以下的示例建立在ASP.NET MVC ...

  6. asp.net MVC之 自定义过滤器(Filter)

    一.系统过滤器使用说明 1.OutputCache过滤器 OutputCache过滤器用于缓存你查询结果,这样可以提高用户体验,也可以减少查询次数.它有以下属性: Duration:缓存的时间,以秒为 ...

  7. [转]ASP.NET MVC中你必须知道的13个扩展点

    本文转自:http://www.cnblogs.com/ejiyuan/archive/2010/03/09/1681442.html ScottGu在其最新的博文中推荐了Simone Chiaret ...

  8. Asp.net mvc 中Action 方法的执行(一)

    [toc] 在 Aps.net mvc 应用中对请求的处理最终都是转换为对某个 Controller 中的某个 Action 方法的调用,因此,要对一个请求进行处理,第一步,需要根据请求解析出对应的 ...

  9. Asp.net mvc 中的 Controller 的激活

    Controller 激活是指根据路由系统解析出来的 Controller 的名称创建 控制器(Controller)的过程,这里的控制器泛指实现了 IController 接口的类型 激活过程中的核 ...

随机推荐

  1. Java日期时间API系列7-----Jdk8中java.time包中的新的日期时间API类的特点

    1.不变性 新的日期/时间API中,所有的类都是不可变的,这对多线程环境有好处. 比如:LocalDateTime 2.关注点分离 新的API将人可读的日期时间和机器时间(unix timestamp ...

  2. Promise简单使用,需要在ES6以上

     //Promise延时顺序执行 var waitOne = new Promise(function(resolve, reject) { setTimeout(function(){ resolv ...

  3. Mysql—主从复制

    https://www.jb51.net/article/137925.htm https://blog.51cto.com/13706760/2171361 https://www.cnblogs. ...

  4. UGUI Manual

    以Unity 5.5 的官方文档为例 Canvas UI元素的前后顺序:SetAsFirstSibling, SetAsLastSibling, and SetSiblingIndex BasicLa ...

  5. 6. Go语言—字符串操作

    一.字符串支持的转义字符 \r 回车符(返回行首) \n 换行符(直接跳到下一行的同列位置) \t 制表符 \' 单引号 \" 双引号 \\ 反斜杠 \uXXXX Unicode字符码值转义 ...

  6. node exporter

    在prometheus中负责数据汇报的程序统一叫做exporter; 负责主机信息收集的node_exporter 可以利用prometheus的static_configs来拉取node_expor ...

  7. jmeter从上一个请求使用正则表达式抓取Set-Cookie值,在下一个请求中运用

    工作中遇到的问题,登录请求,返回的Response Headers中有个参数Set-Cookie,需要抓取这个参数,运用到下一个请求中,见下图: 通过正则表达式抓取Set-Cookie的值,由于该值存 ...

  8. apache配置文件详解(中英文对照版)

    # This is the main Apache server configuration file. It contains the # configuration directives that ...

  9. Java基本数据类型转换二

    public class TestConvert2 { /** * @param args */ public static void main(String[] args) { // TODO Au ...

  10. wafer2-nodejs 本地部署服务器

    友情提示:假设你已经部署好了腾讯云微信小程序服务,如果没有,就不用往下看了,果断选云开发. ------------------------------------------------------ ...