AspMvc(Filter及其执⾏顺序)
应⽤于Action的Filter
在AspMvc中当你有以下及类似以下需求时你可以使⽤Filter功能
判断登录与否或⽤户权限,决策输出缓存,防盗链,防蜘蛛,本地化设置,实现动态Action
filter是⼀种声明式编程⽅式,在Asp 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"] %>
这样我们就可以执⾏这个页⾯了
mvc的controller在第⼀次执⾏完成后,页⾯显⽰
OnActionExecuting
Action
这证明是先执⾏了OnActionExecuting然后执⾏了Action,我们再刷新⼀下页⾯
则得到
OnActionExecuting
Action
OnActionExecuted
OnActionExecuting
Action
这是因为OnActionExecuted是在第⼀次页⾯显⽰后才执⾏,所以要到第⼆次访问页⾯时才能看到
Controller的Filter
Monorail中的Filter是可以使⽤在Controller中的,这给编程者带来了很多⽅便,那么在Asp 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的具体⽣存周期
这是官⽅站的⼀数据.
1. 来⾃controller虚⽅法的OnActionExecuting .
2. 应⽤于当前Controller的Filter中的OnActionExecuting:
先执⾏基类的,后执派⽣类的
3. 执⾏应⽤于Action的Filter的OnActionExecuting顺序:
先执⾏基类的,后执派⽣类的
4. Action ⽅法
5. 应⽤于Action的Filter的OnActionExecuted 的执⾏顺序
先执⾏派⽣类的,后执⾏基类的
6. 应⽤于当前Controller的Filter中的OnActionExecuted⽅法
先执⾏派⽣类的,后执⾏基类的
7. Controller中的虚⽅法 OnActionExecuted