1. 程式人生 > >Asp.net Mvc Framework 七 (Filter及其執行順序)

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
{
    
publicclass TestFilter : ActionFilterAttribute
    
{
        
publicoverridevoid OnActionExecuting(FilterExecutingContext
           filterContext) 
{
            filterContext.HttpContext.Session[
"temp"+="OnActionExecuting<br/>
";
        }


        
publicoverridevoid OnActionExecuted(FilterExecutedContext
            filterContext) 
{
            filterContext.HttpContext.Session[
"temp"+="OnActionExecuted<br/>";
        }

    }

}

在這裡我們在Session["temp"]上標記執行的順序
我們在Controller中的Action中寫以下程式碼
        [TestFilter]
        
publicvoid 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;
    
publicclass EiceController : Controller
    
{
        
publicvoid Index() {        this.HttpContext.Session["temp"+="Action<br/>";

            RenderView(
"Index");
        }

        
publicvoid Index2() {
            
            RenderView(
"Index");
        }

        
protectedoverridevoid OnActionExecuting(FilterExecutingContext
           filterContext) 
{
            filterContext.HttpContext.Session[
"temp"+="OnActionExecuting<br/>";
        }


        
protectedoverridevoid 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
Asp.net Mvc Framework 系列