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方法

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace MvcApplication2.Filters
{
public class LoginAttribute:AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
//如果Session中不存在该值,那么表示没有登录
if (filterContext.HttpContext.Session["User"] == null)
{
filterContext.Result = new RedirectResult("/Account/Login");
}
}
}
}

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

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

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

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

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication2.Filters; namespace MvcApplication2.Controllers
{
public class HomeController : Controller
{
//在方法上加入授权特性
[Login]
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; return View();
} public ActionResult About()
{
ViewBag.Message = "Your app description page."; return View();
} public ActionResult Contact()
{
ViewBag.Message = "Your contact page."; return View();
}
}
}

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

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

 using System.Web;
using System.Web.Mvc;
using MvcApplication2.Filters; namespace MvcApplication2.Controllers
{
[Login]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; return View();
} public ActionResult About()
{
ViewBag.Message = "Your app description page."; return View();
} public ActionResult Contact()
{
ViewBag.Message = "Your contact page."; return View();
}
}
}

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

3、注册全局过滤器

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

 using System.Web;
using System.Web.Mvc; namespace MvcApplication2
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
//在此处添加需要注册的全局过滤器
filters.Add(new MvcApplication2.Filters.LoginAttribute());
}
}
}

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

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

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace MvcApplication2.Filters
{
public class LoginAttribute:AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
//获取当前相对项目的更目录的路径
string path = filterContext.HttpContext.Request.CurrentExecutionFilePath;
if(!path.StartsWith("/Account/", StringComparison.CurrentCultureIgnoreCase))
{
//如果Session中不存在该值,那么表示没有登录
if (filterContext.HttpContext.Session["User"] == null)
{
filterContext.Result = new RedirectResult("/Account/Login");
}
} }
}
}

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

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

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

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

四、异常过滤器

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

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace MvcApplication2.Filters
{
public class MyExceptionAttribute:HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
base.OnException(filterContext); //填写验证信息,记录错误日志 //跳转到错误页面
filterContext.Result = new RedirectResult("/Error");
}
}
}

  这里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. 【Android界面实现】FragmentPagerAdapter与FragmentStatePagerAdapter使用详解与区别

    转载请注明出处: http://blog.csdn.net/zhaokaiqiang1992 FragmentPagerAdapter是android-support-v4支持包里面出现的一个新的适配 ...

  2. Microsoft SQL Server

    instance / database / schema / object login / user / schema (dbo) sequence Collation PSM: Both Insta ...

  3. Jni碰到的一个异常

    Java与C++都有String对象,而c没有,只有char类型,所以在向C传入String类型的时候,如何处理需要注意一点 jstring Java_com_skymaster_hs_test4_M ...

  4. Element can be click when out of view

    WebDriver can't action the element when out of view Webdriver can't action the element when the elem ...

  5. 配置NGReport 报告中文

    1. 测试报告的名称 在测试开始或测试监听器的类中加上下面一句代码即可: System.setProperty("org.uncommons.reportng.title", &q ...

  6. C语言编译器 cc 编译原理

    生成一个可执行的文件通常需要经过以下几个步骤: 预处理你的源代码,去掉注释,以及其他技巧性的工作就像在 C 中展开宏. 检查代码的语法看你是否遵守了这个语言的规则.如果没有,编译器会给出 警告. 把源 ...

  7. linux笔记:linux软件包管理,软件安装位置

    linux软件包简介 软件包分类:1.源码包(用C语言等编写的源代码,没有进行编译):脚本安装包(对源码包进行了安装优化的源码包)优点:开源,可修改可以自由选择所需的功能编译安装,更适合自己的系统,稳 ...

  8. db:seed 更好的生成测试数据

    make:model -m -> 在database/migrations/目录下生成的table表中设置表的字段名和字段类型->在app/目录下对应的模型文件中设置可添加字段 -> ...

  9. js 判断当前的手机系统类型

    <script language="javascript">window.onload = function () {alert("1");var ...

  10. jq实现楼层切换效果

    <!DOCTYPE html> <html> <head> <style> * { margin: 0; padding: 0; box-sizing: ...