2010-11-05 99 views
2

嗨我有一些代碼需要運行一次的請求。我有一個BaseController,所有控制器派生自。我將我的代碼寫入BaseController onActionExecuting方法,但它不好,因爲對於每個操作,執行代碼都在運行。我可以用一個基本的if子句預製它,但我不想像那樣使用它。運行一次請求最好的地方在哪裏?

什麼是運行代碼1次請求的最佳位置。我也想到達HttpContext,我寫這個代碼。謝謝

+0

在ASP.NET MVC控制器動作總是與HTTP請求相關。所以OnActionExecuting保證代碼每個請求只執行一次。如果這不是你想要的,請進一步解釋。 – 2010-11-05 17:58:42

+0

這是事實,但不適合我。因爲在我的視圖中,我有很多Render.Action,所以當它觸及Render.Action時,BaseController.OnActionExecuting會重新運行。 – Yucel 2010-11-05 18:32:11

回答

6

在您對有關子操作的評論之後,您可以測試當前操作是否爲子操作並且不執行代碼。所以你可以有一個自定義動作過濾器:

public class CustomFilterAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     // this method happens before calling the action method 

     if (!filterContext.IsChildAction) 
     { 
      // this is not the a child action => do the processing 
     } 
     base.OnActionExecuting(filterContext); 
    } 
} 

然後用這個自定義屬性來修飾你的基礎控制器。類似的測試可以在你的基地控制器的重寫OnActionExecuting方法,如果你喜歡它,而不是行動的執行屬性:

protected override void OnActionExecuting(ActionExecutingContext filterContext) 
{ 
    if (!filterContext.IsChildAction) 
    { 
     // this is not the a child action => do the processing 
    } 
    base.OnActionExecuting(filterContext); 
} 
+0

第二個代碼更好,我不想爲所有操作添加屬性,謝謝你的解脫。 – Yucel 2010-11-07 18:39:27

+0

您不需要爲所有操作添加屬性。只需修飾基礎控制器類,它將應用於所有操作和所有派生控制器操作。 – 2010-11-07 19:30:20

+0

嗯好的解決方案謝謝.. – Yucel 2010-11-09 14:16:38

相關問題