您的位置:首页 > 编程语言 > ASP

Asp.net Mvc Framework 七 (Filter及其执行顺序)

2008-03-12 15:11 459 查看
应用于Action的Filter

在Asp.netMvc中当你有以下及类似以下需求时你可以使用Filter功能
判断登录与否或用户权限,决策输出缓存,防盗链,防蜘蛛,本地化设置,实现动态Action
filter是一种声明式编程方式,在Asp.net MVC中它只能应用在Action上
Filter要继承于ActionFilterAttribute抽象类,并可以覆写void OnActionExecuting(FilterExecutingContext)和
void OnActionExecuted(FilterExecutedContext)这两个方法
OnActionExecuting是Action执行前的操作,OnActionExecuted则是Action执行后的操作

下面我给大家一个示例,来看看它的的执行顺序

首先我们先建立 一个Filter,名字叫做TestFilter


using System.Web.Mvc;





namespace MvcApplication2.Controllers






{


public class TestFilter : ActionFilterAttribute






{


public override void OnActionExecuting(FilterExecutingContext




filterContext)

{


filterContext.HttpContext.Session["temp"] += "OnActionExecuting<br/>";


}





public override void OnActionExecuted(FilterExecutedContext




filterContext)

{


filterContext.HttpContext.Session["temp"] += "OnActionExecuted<br/>";


}


}


}



在这里我们在Session["temp"]上标记执行的顺序
我们在Controller中的Action中写以下代码


[TestFilter]




public void Index()

{


this.HttpContext.Session["temp"] += "Action<br/>";


RenderView("Index");


}
在这个Action执行的时候,我们也为Session["temp"]打上了标记.

最后是View的内容
很简单我们只写


<%=Session["temp"] %>
这样我们就可以执行这个页面了
在第一次执行完成后,页面显示

OnActionExecuting
Action
这证明是先执行了OnActionExecuting然后执行了Action,我们再刷新一下页面
则得到


OnActionExecuting


Action


OnActionExecuted


OnActionExecuting


Action
这是因为OnActionExecuted是在第一次页面 显示后才执行,所以要到第二次访问页面时才能看到
Controller的Filter
Monorail中的Filter是可以使用在Controller中的,这给编程者带来了很多方便,那么在Asp.net MVC中可不可以使用Controller级的Filter呢.不言自喻.

实现方法如下Controller本身也有OnActionExecuting与OnActionExecuted方法 ,将之重写即可,见代码



namespace MvcApplication2.Controllers






{


using System.Web.Mvc;


public class EiceController : Controller






{




public void Index()

{ this.HttpContext.Session["temp"] += "Action<br/>";





RenderView("Index");


}




public void Index2()

{





RenderView("Index");


}


protected override void OnActionExecuting(FilterExecutingContext




filterContext)

{


filterContext.HttpContext.Session["temp"] += "OnActionExecuting<br/>";


}





protected override void OnActionExecuted(FilterExecutedContext




filterContext)

{


filterContext.HttpContext.Session["temp"] += "OnActionExecuted<br/>";


}


}


}

这里要注意一点,这两个方法 一定要protected
要是想多个Controller使用这个Filter怎么办?继承呗.
Filter的具体生存周期
这是官方站的一数据.


来自controller虚方法 的OnActionExecuting .




应用于当前Controller的Filter中的OnActionExecuting:

先执行基类的,后执派生类的


执行应用于Action的Filter的OnActionExecuting顺序:

先执行基类的,后执派生类的





Action 方法





应用于Action的Filter的OnActionExecuted 的执行顺序


先执行派生类的,后执行基类的


应用于当前Controller的Filter中的OnActionExecuted方法

先执行派生类的,后执行基类的


Controller中的虚方法 OnActionExecuted




示例可见http://quickstarts.asp.net/3-5-extensions/mvc/ActionFiltering.aspx

Asp.net Mvc Framework 系列
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: