在Asp.netMvc中當你有以下及類似以下需求時你可以使用Filter功能
判斷登錄與否或用戶權限,決策輸出緩存,防盜鏈,防蜘蛛,本地化設置,實現動態Action
filter是一種聲明式編程方式,在Asp.net MVC中它只能應用在Action上
Filter要繼承於ActionFilterAttribute抽象類,並可以覆寫void OnActionExecuting(FilterExecutingContext)和
void OnActionExecuted(FilterExecutedContext)這兩個方法
OnActionExecuting是Action執行前的操作,OnActionExecuted則是Action執行後的操作
下面我給大家一個示例,來看看它的的執行順序
首先我們先建立 一個Filter,名字叫做TestFilter
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/>";
}
}
}
我們在Controller中的Action中寫以下代碼
public void Index() {
this.HttpContext.Session["temp"] += "Action<br/>";
RenderView("Index");
}
最後是View的內容
很簡單我們只寫
在第一次執行完成後,頁面顯示
Action
則得到
Action
OnActionExecuted
OnActionExecuting
Action
Controller的Filter
Monorail中的Filter是可以使用在Controller中的,這給編程者帶來了很多方便,那麼在Asp.net MVC中可不可以使用Controller級的Filter呢.不言自喻.
實現方法如下Controller本身也有OnActionExecuting與OnActionExecuted方法 ,將之重寫即可,見代碼
{
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/>";
}
}
}
要是想多個Controller使用這個Filter怎麼辦?繼承唄.
Filter的具體生存週期
這是官方站的一數據.
-
來自controller虛方法 的OnActionExecuting .
-
應用於當前Controller的Filter中的OnActionExecuting:
先執行基類的,後執派生類的 -
執行應用於Action的Filter的OnActionExecuting順序:
先執行基類的,後執派生類的 -
Action 方法
-
應用於Action的Filter的OnActionExecuted 的執行順序
先執行派生類的,後執行基類的 -
應用於當前Controller的Filter中的OnActionExecuted方法
先執行派生類的,後執行基類的 -
Controller中的虛方法 OnActionExecuted