本文主要介绍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. CSS链接、光标、DHTML、缩放

    个属性 18.2 CSS中光标的使用(更详细可看文档) 属性名称                属性值                说明 cursor                 auto    ...

  2. 【Stage3D学习笔记续】山寨Starling(八):核心优化(批处理)的实现

    批处理是使GPU进行高效绘制的一种技术手段,也是整个渲染流程中最核心的技术,到目前为止我们并没有使用到这种技术手段,下面我们看看我们现在的渲染机制. 先想一想我们最开始是怎么向GPU绘制一幅图像的,可 ...

  3. Delphi- ini文件的读写操作

    一.读INI文件示例 procedure TForm1.FormCreate(Sender: TObject); Var MyIni :Tinifile; glAppPath :string; beg ...

  4. centos6下安装部署hadoop2.2

    环境准备1.操作系统:centos6.0 64位2.hadoop版本:hahadoop-2.2.0 安装和配置步骤具体如下:1.主机和ip分配如下     ip地址                  ...

  5. iOS containsString与rangeOfString

    rangeOfString是在 containsString没出来之前 用于查找字符串中是否包含某字符,iOS <8.0 NSString *str1 = @"can you \n s ...

  6. Java设计模式学习资源汇总

    本文记录了Java设计模式学习书籍.教程资源.此分享会持续更新: 1. 设计模式书籍 在豆瓣上搜索了一把,发现设计模式贯穿了人类生活的方方面面.还是回到Java与程序设计来吧. 打算先归类,再浏览,从 ...

  7. PHP中的正则表达式函数preg_

    preg_match();     //用于正则表达式的匹配,且只匹配一次 preg_match_all();//用于正则表达式的匹配,会对所有符合规则的都进行匹配 preg_replace();   ...

  8. 学习笔记之#pragma

    http://baike.baidu.com/link?url=lxA9Wl1KnacWUDZYz5U06iKMkUAeI6dr0x1wQ4i-rqf6Dpk6hEeOOaj2XhvGx9VLVm2z ...

  9. [MethodImpl(MethodImplOptions.Synchronized)]

    在NopCommerce项目的Nop.Core类库中有一个EngineContext类中有一个Initialize方法用到了[MethodImpl(MethodImplOptions.Synchron ...

  10. javascript笔记04:let语句 和 yield语句 和 with语句

    1.yield语句: <script type="application/javascript; version=1.7"> function generator() ...