Asp.net Mvc Framework 七 (Filter及其執行順序)

 應用於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的具體生存週期
這是官方站的一數據.
  1. 來自controller虛方法 的OnActionExecuting .

  2. 應用於當前Controller的Filter中的OnActionExecuting:

    先執行基類的,後執派生類的
  3. 執行應用於Action的Filter的OnActionExecuting順序:

    先執行基類的,後執派生類的

  4. Action 方法

  5. 應用於Action的Filter的OnActionExecuted 的執行順序

    先執行派生類的,後執行基類的
  6. 應用於當前Controller的Filter中的OnActionExecuted方法

    先執行派生類的,後執行基類的
  7. Controller中的虛方法 OnActionExecuted

示例可見http://quickstarts.asp.net/3-5-extensions/mvc/ActionFiltering.aspx
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章