MVC过滤器是加在 Controller 或 Action 上的一种 Attribute,通过过滤器,MVC 网站在处理用户请求时,可以处理一些附加的操作,如:用户权限验证、系统日志、异常处理、缓存等。MVC 中包含Authorization filter、Action filter、Result filter、Exception filter 四种过滤器。

  APS.NET MVC中的每一个请求,都会分配给相应的控制器和对应的行为方法去处理,而在这些处理的前前后后如果想再加一些额外的逻辑处理。这时候就用到了过滤器。

一、MVC支持的过滤器类型有四种:

  Authorization(授权)

  Action(行为)

  Result(结果)

  Exception(异常)

滤器类型

接口

描述

Authorization

IAuthorizationFilter

此类型(或过滤器)用于限制进入控制器或控制器的某个行为方法

Exception

IExceptionFilter

用于指定一个行为,这个被指定的行为处理某个行为方法或某个控制器里面抛出的异常

Action

IActionFilter

用于进入行为之前或之后的处理

Result

IResultFilter

用于返回结果的之前或之后的处理

 

  但是默认实现它们的过滤器只有三种,分别是Authorize(授权),ActionFilter,HandleError(错误处理);各种信息如下表所示

二、使用Filter的方式

  1、通过特性的方式使用Filter

  2、通过重写Controller方法来使用Filter

三、Authorize过滤器

方法一:使用特性的方式

  定义一个类,继承与AuthorizeAttribute,并重写OnAuthorization方法

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6.  
  7. namespace MvcApplication2.Filters
  8. {
  9. public class LoginAttribute:AuthorizeAttribute
  10. {
  11. public override void OnAuthorization(AuthorizationContext filterContext)
  12. {
  13. //如果Session中不存在该值,那么表示没有登录
  14. if (filterContext.HttpContext.Session["User"] == null)
  15. {
  16. filterContext.Result = new RedirectResult("/Account/Login");
  17. }
  18. }
  19. }
  20. }

  这里判断如果,用户没有登录,那么需要返回到登录界面。

  虽然定义了一个过滤器,但是还需使用过滤器

使用过滤器的方式也有几种方式:

1、在方法前加上授权特性

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using MvcApplication2.Filters;
  7.  
  8. namespace MvcApplication2.Controllers
  9. {
  10. public class HomeController : Controller
  11. {
  12. //在方法上加入授权特性
  13. [Login]
  14. public ActionResult Index()
  15. {
  16. ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
  17.  
  18. return View();
  19. }
  20.  
  21. public ActionResult About()
  22. {
  23. ViewBag.Message = "Your app description page.";
  24.  
  25. return View();
  26. }
  27.  
  28. public ActionResult Contact()
  29. {
  30. ViewBag.Message = "Your contact page.";
  31.  
  32. return View();
  33. }
  34. }
  35. }

  这种方式,只能对有加上该授权特性的方法进行登录检查,其它没有加的方法无法进行过滤。在上面代码中,只能对该controller中index的action进行过滤,另外的About和Contact无法过滤。

2、在类上加特性,那么表示对该类下所有方法加上该特性

  1. using System.Web;
  2. using System.Web.Mvc;
  3. using MvcApplication2.Filters;
  4.  
  5. namespace MvcApplication2.Controllers
  6. {
  7. [Login]
  8. public class HomeController : Controller
  9. {
  10. public ActionResult Index()
  11. {
  12. ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
  13.  
  14. return View();
  15. }
  16.  
  17. public ActionResult About()
  18. {
  19. ViewBag.Message = "Your app description page.";
  20.  
  21. return View();
  22. }
  23.  
  24. public ActionResult Contact()
  25. {
  26. ViewBag.Message = "Your contact page.";
  27.  
  28. return View();
  29. }
  30. }
  31. }

  这种方式虽然不用对每个方法都添加特性,但是也只是对在类上加上了该特性的Controller有作用,其它没有加的会无效

3、注册全局过滤器

  在实际项目中,一个项目往往会有很多的Controller和Action那么,如果向上面的两种方式来出来都不够理性,通常我们使用全局过滤器。使用方式

  1. using System.Web;
  2. using System.Web.Mvc;
  3.  
  4. namespace MvcApplication2
  5. {
  6. public class FilterConfig
  7. {
  8. public static void RegisterGlobalFilters(GlobalFilterCollection filters)
  9. {
  10. //在此处添加需要注册的全局过滤器
  11. filters.Add(new MvcApplication2.Filters.LoginAttribute());
  12. }
  13. }
  14. }

  这样就不用再每个类上添加Login过滤器了,默认对每个Controller的每个Action都使用该特性。但是有个问题,就是连登陆页面也被过滤掉了。在这里使用AllowAnonymous都无效

   可以在自定义Filter时,通过获取当前访问路径,判断是否是需要排除的路径,如果是,则跳过

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6.  
  7. namespace MvcApplication2.Filters
  8. {
  9. public class LoginAttribute:AuthorizeAttribute
  10. {
  11. public override void OnAuthorization(AuthorizationContext filterContext)
  12. {
  13. //获取当前相对项目的更目录的路径
  14. string path = filterContext.HttpContext.Request.CurrentExecutionFilePath;
  15. if(!path.StartsWith("/Account/", StringComparison.CurrentCultureIgnoreCase))
  16. {
  17. //如果Session中不存在该值,那么表示没有登录
  18. if (filterContext.HttpContext.Session["User"] == null)
  19. {
  20. filterContext.Result = new RedirectResult("/Account/Login");
  21. }
  22. }
  23.  
  24. }
  25. }
  26. }

  这里,以/Account/开始的请求都不会执行该授权过滤器。

方法二:使用重写Controller方法的方式

  1. protected override void OnAuthorization(AuthorizationContext filterContext)
  2. {
  3. //自定义授权验证代码
  4. }

  这种方式相当于在类上使用授权特性,对于该Controller下的所有方法都有效

四、异常过滤器

  需要继承与HandleErrorAttribute,并重写OnException方法

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6.  
  7. namespace MvcApplication2.Filters
  8. {
  9. public class MyExceptionAttribute:HandleErrorAttribute
  10. {
  11. public override void OnException(ExceptionContext filterContext)
  12. {
  13. base.OnException(filterContext);
  14.  
  15. //填写验证信息,记录错误日志
  16.  
  17. //跳转到错误页面
  18. filterContext.Result = new RedirectResult("/Error");
  19. }
  20. }
  21. }

  这里base.OnException(filterContext)不能省略,否则无法捕获到异常

  同时在web.config文件中需要配置,启用自定义异常。    <customErrors mode="On"></customErrors>

五、行为和结果过滤器

  这两种过滤器都是继承于ActionFilterAttribute类

  行为过滤器:需要选择重写OnActionExecuting或者OnActionExecuted,至于是哪个方法看需求,也可以哪个方法都重写

  结果过滤器:需要选择重写OnResultExecuting或者OnResultExecuted,至于是哪个方法看需求,也可以哪个方法都重写

  

ASP.NET MVC过滤器(一)的更多相关文章

  1. ASP.NET MVC 过滤器(一)

    ASP.NET MVC 过滤器(一) 前言 前面的篇幅中,了解到了控制器的生成的过程以及在生成的过程中的各种注入点,按照常理来说篇幅应该到了讲解控制器内部的执行过程以及模型绑定.验证这些知识了.但是呢 ...

  2. ASP.NET MVC 过滤器(三)

    ASP.NET MVC 过滤器(三) 前言 本篇讲解行为过滤器的执行过程,过滤器实现.使用方式有AOP的意思,可以通过学习了解过滤器在框架中的执行过程从而获得一些AOP方面的知识(在顺序执行的过程中, ...

  3. ASP.NET MVC 过滤器(四)

    ASP.NET MVC 过滤器(四) 前言 前一篇对IActionFilter方法执行过滤器在框架中的执行过程做了大概的描述,本篇将会对IActionFilter类型的过滤器使用来做一些介绍. ASP ...

  4. ASP.NET MVC 过滤器(五)

    ASP.NET MVC 过滤器(五) 前言 上篇对了行为过滤器的使用做了讲解,如果在控制器行为的执行中遇到了异常怎么办呢?没关系,还好框架给我们提供了异常过滤器,在本篇中将会对异常过滤器的使用做一个大 ...

  5. ASP.NET没有魔法——ASP.NET MVC 过滤器(Filter)

    上一篇文章介绍了使用Authorize特性实现了ASP.NET MVC中针对Controller或者Action的授权功能,实际上这个特性是MVC功能的一部分,被称为过滤器(Filter),它是一种面 ...

  6. Asp.net Mvc 过滤器执行顺序

    Asp.net Mvc 过滤器执行顺序: IAuthorizationFilter(OnAuthorization)----->IActionFilter(OnActionExecuting)- ...

  7. ASP.NET MVC过滤器

    在ASP.NET MVC中有个重要特性就是过滤器,使得我们在MVC程序开发中更好的控制浏览器请求的URL,不是每个请求都有响应内容,只有特定得用户才有.园子里关于过滤器的资料也有很多,这篇文章主要是记 ...

  8. ASP.NET MVC 过滤器开发与使用

    ASP.NET MVC 中给我们提供了内置的过滤器,通过过滤器,我们可以在控制器内的方法前后,添加必须的业务逻辑,如权限验证,身份验证,错误处理等. 今天,我们主要介绍3个过滤器:OutputCach ...

  9. Asp.Net MVC过滤器小试牛刀

    在上学期间学习的Asp.Net MVC,基本只是大概马马虎虎的了解,基本处于知其然而不知其所以然.现在到上班,接触到真实的项目,才发现还不够用,于是从最简单的过滤器开始学习.不得不说MVC的过滤器真是 ...

随机推荐

  1. 2014 Multi-University Training Contest 1

    A hdu4861 打表找规律 #include <iostream> #include<cstdio> #include<cstring> #include< ...

  2. cheat-linux命令行实用助记工具

    cheat究竟用来干嘛? 我们虽然能够使用man和--help来帮助我们查看命令使用方式,但是很多工程师都觉得,他们显然还不够man! 看看cheat是怎么man的 当我敲下cheat tar的时候, ...

  3. 对于syncedmen类的代码分析

    对于数据在cpu与GPU之间同步的问题,caffe中用syncedMemory这个类来解 决:在GPU模式下,并且使用CUDA时,可以用CaffeMallocHost函数与CaffeFreeHost函 ...

  4. JavaWeb 7 Servlet

    7 Servlet Servlet学习的大纲:1. servlet概念及相关接口简介2. servet 执行过程3. servlet路径映射4. 缺省servlet          --应用5. s ...

  5. 转:如何学习SQL(第四部分:DBMS扩展功能与SQL高级话题)

    转自:http://blog.163.com/mig3719@126/blog/static/285720652010950102575/ 9. DBMS提供的扩展功能 掌握了基本的关系模型原理和DB ...

  6. listview某一项不可点击

    listview 整个都不可操作 listview.setEnable(false); listview 某一项不可点击 重写 isEnable()方法,在方法内部判断position,不可点击的项 ...

  7. imeOptions 属性详解

    默认情况下软键盘右下角的按钮为“下一个”,点击会到下一个输入框,保持软键盘 设置 android:imeOptions="actionDone" ,软键盘下方变成“完成”,点击后光 ...

  8. root的方法大体上有以下三种

    root的方法大体上有以下三种一.手机软件安卓版直接root.这种方法不需要电脑的支持,也很安全.安卓版软件有:kingroot,360一键root,一键root大师,Towelroot,支持云roo ...

  9. java 导入包(误区)

    java的导入包语句的作用仅仅是简化书写,很多时候我们都误以为是将一个类导入到内存中. 如果是这样,那么运行的效率会很慢.

  10. VMware Workstation 无法连接到虚拟机

    "This PC(我的电脑)":右键"manage(管理)": "Service and Applications(服务和应用)":&quo ...