本文主要介绍ASP.NET MVC中的Action Filters,并通过举例来呈现其实际应用。

Action Filters 可以作为一个应用,作用到controller action (或整个controller action中),以改变action的行为。

ASP.NET MVC Framework支持四种不同类型的Filter:

  1. Authorization filters – 实现IAuthorizationFilter接口的属性.
  2. Action filters – 实现IActionFilter接口的属性.
  3. Result filters – 实现IResultFilter接口的属性.
  4. Exception filters – 实现IExceptionFilter接口的属性。

Filter 的默认执行顺序,如上面的编号顺序。验证(authorization)filter永远都是最开始执行的,异常(exception)filter永远都是最后执行的。

下面只详细介绍Action Filters。

在Action Filters中 ASP.NET MVC Framework 提供了ActionFilterAttribute父类。

所以在Action,Result执行之前之后分别做一些操作,就需要重写ActionFilterAttribute父类,并实现父类中的虚方法。

下面,我们假设一种场景。当我们打开管理系统的页面时,需要进行权限检查,假如多个页面都需要权限检查,重复的代码,必然会让我们感到抓狂。

这时候就可以利用ActionFilterAttribute父类重写OnActionExecuting()方法进行权限检查。

首先,我们在App_Start中添加一个新类,继承ActionFilterAttribute父类。代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace MvcMobileDMS.App_Start
{
//[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
public class ActionAttributeFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{ //在Action执行前执行
if (filterContext.HttpContext.Session["temp"] == null)
{
filterContext.HttpContext.Response.Redirect("~/dms/logon");
}
//filterContext.HttpContext.Response.Redirect("dms/add"); base.OnActionExecuting(filterContext);
}
}
}

我们假设当系统中存在Session["temp"],则验证通过。否则跳到登陆页面。

好了,ActionFilterAttribute父类已经重写,那么如何运用到我们的Action中呢?很简单,看代码:

 [MvcMobileDMS.App_Start.ActionAttributeFilter()]
public ActionResult Add()
{
Session.Remove("temp");
return View();
}

在Action 方法上添加[MvcMobileDMS.App_Start.ActionAttributeFilter()]即可。即我们新增的类。这样每次访问add页面就要做权限检查。

那么,我们再想深一层,假如我想所有的页面都执行权限检查呢?看代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace MvcMobileDMS.Controllers
{
[MvcMobileDMS.App_Start.ActionAttributeFilter()]
public class DMSController : Controller
{
//
// GET: /DMS/
//[MvcMobileDMS.App_Start.ActionAttributeFilter()]
public ActionResult Index()
{ //AVON.DMS.DAL.Entities DMS = new AVON.DMS.DAL.Entities();
//AVON.DMS.Model.REP A = DMS.REP.SingleOrDefault<AVON.DMS.Model.REP>(t => t.NO == "00561874");
//AVON.DMS.BLL.Rep repBLL = new AVON.DMS.BLL.Rep();
//AVON.DMS.Model.REP A = repBLL.GetFromRep("00561874");
//ViewData["mydata"] = A.JOINDATE;
ViewData["mydata"] = "index";
return View();
} //[MvcMobileDMS.App_Start.ActionAttributeFilter()]
public ActionResult Add()
{
Session.Remove("temp");
return View();
} public ActionResult logon()
{
Session["temp"] = "aaa";
return View();
} public string test()
{
return "hahah";
}
}
}

在DMSController类前,我添加了[MvcMobileDMS.App_Start.ActionAttributeFilter()],如此,所有的action在运行前都会执行OnActionExecuting方法,即权限检查。

如果,我们再更想深一层,我们想所有的Controller都执行呢?也很简单,只需修改Global.asax代码,如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing; namespace MvcMobileDMS
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalFilters.Filters.Add(new MvcMobileDMS.App_Start.ActionAttributeFilter());
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}

只要添加全局GlobalFilter即可。GlobalFilters.Filters.Add(new MvcMobileDMS.App_Start.ActionAttributeFilter());

希望对你有所帮助O(∩_∩)O哈哈~。

Action Filters for ASP.NET MVC的更多相关文章

  1. 8. Filters in ASP.NET MVC 5.0【ASP.NET MVC 5.0中的过滤器】

    ASP.NET Filers用来在MVC框架的不同请求处理阶段,注入额外的逻辑.过滤器为横切关注点提供了一种方法(日志记录,授权,缓存). 在这篇文章中,我将会向你介绍MVC框架支持的各种不同种类过滤 ...

  2. 获取action name在asp.net mvc

    Update for MVC 3 ViewContext.Controller.ValueProvider.GetValue("action").RawValue ViewCont ...

  3. Asp.net MVC十问十答[译]

    1. Explain MVC (Model-View-Controller) in general? MVC (Model-View-Controller) is an architectural s ...

  4. 理解ASP.NET MVC Framework Action Filters

    原文:http://www.cnblogs.com/darkdawn/archive/2009/03/13/1410477.html 本指南主要解释action filters,action filt ...

  5. HTTP Modules versus ASP.NET MVC Action Filters

    from:http://odetocode.com/blogs/scott/archive/2011/01/17/http-modules-versus-asp-net-mvc-action-filt ...

  6. ASP.NET MVC的Action Filter

    一年前写了一篇短文ASP.NET MVC Action Filters,整理了Action Filter方面的资源,本篇文章详细的描述Action Filter.Action Filter作为一个可以 ...

  7. ASP.NET MVC 4.0的Action Filter

    有时候你想在调用action方法之前或者action方法之后处理一些逻辑,为了支持这个,ASP.NET MVC允许你自定义创建action过滤器.Action过滤器是自定义的Attributes,用来 ...

  8. ASP.NET MVC和ASP.NET Core MVC中获取当前URL/Controller/Action (转载)

    ASP.NET MVC 一.获取URL(ASP.NET通用): [1]获取完整url(协议名+域名+虚拟目录名+文件名+参数) string url=Request.Url.ToString(); [ ...

  9. Asp.net mvc 知多少(八)

    本系列主要翻译自<ASP.NET MVC Interview Questions and Answers >- By Shailendra Chauhan,想看英文原版的可访问[http: ...

随机推荐

  1. 制作第三方SDK静态库、.framework

    静态库和动态库的存在形式 静态库: .a 和 .framework 动态库: .dylib 和 .framework 静态库和动态库的使用区别: 静态库:链接时,静态库会被完整地复制 到 可执行文件中 ...

  2. 利用putty软件连接虚拟机中linux操作系统

    http://jingyan.baidu.com/article/9c69d48fbefe6613c8024e6a.html 大家在使用虚拟的过程中有时候会感觉切换操作系统很不方便,那么有什么方法可以 ...

  3. hbase运维

    NoSQL现在风生水起,hbase的使用也越来越广,但目前几乎所有的NoSQL产品在运维上都没法和DB相提并论,在这篇blog中来总结下我们在运维hbase时的一些问题以及解决的方法,也希望得到更多h ...

  4. 设置UITabBarController的背景颜色

    if (IOS7) { self.tabBarController.tabBar.barTintColor = kTAB_BAR_GB_COLOR; }else{ self.tabBarControl ...

  5. Hdu 5444 Elven Postman dfs

    Elven Postman Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 http://acm.hdu.edu.cn/showproblem.php?pid= ...

  6. 增强的for循环(或foreach)

    增强的for循环(也称为foreach循环):不用下标变量,顺序的訪问整个数组.不能以其它顺序訪问数组,或者改变数组的元素. for(elementType element: arrayRefVar) ...

  7. [AngularJS + cryptoJS + Gravatar] Provider vs factory

    Configurable Bits Need a Provider We want to be able to configure the characterLength before Tweetab ...

  8. .NET下解析Json的方法

    .NET下几种常见的解析JSON方法 主要类 命名空间 限制 内建LINQ支持 DataContractJsonSerializer System.Runtime.Serialization.Json ...

  9. There is no Action mapped for action name XXX. - [unknown location]

    今天被这个问题费了不少时间,原因是缺少了 struts2-json-plugin-2.3.1.2.jar 包 当然,有时候也可能是缺少其他包, 把这个包添加到lib文件夹后还要刷新,clean一下,因 ...

  10. [Effective C++ --014]在资源管理类中小心copying行为

    第一节 <背景> 条款13中讲到“资源取得的时机便是初始化时机”并由此引出“以对象管理资源”的概念.通常情况下使用std中的auto_ptr(智能指针)和tr1::shared_ptr(引 ...