嗨我有一些代碼需要運行一次的請求。我有一個BaseController,所有控制器派生自。我將我的代碼寫入BaseController onActionExecuting方法,但它不好,因爲對於每個操作,執行代碼都在運行。我可以用一個基本的if子句預製它,但我不想像那樣使用它。運行一次請求最好的地方在哪裏?
什麼是運行代碼1次請求的最佳位置。我也想到達HttpContext,我寫這個代碼。謝謝
嗨我有一些代碼需要運行一次的請求。我有一個BaseController,所有控制器派生自。我將我的代碼寫入BaseController onActionExecuting方法,但它不好,因爲對於每個操作,執行代碼都在運行。我可以用一個基本的if子句預製它,但我不想像那樣使用它。運行一次請求最好的地方在哪裏?
什麼是運行代碼1次請求的最佳位置。我也想到達HttpContext,我寫這個代碼。謝謝
在您對有關子操作的評論之後,您可以測試當前操作是否爲子操作並且不執行代碼。所以你可以有一個自定義動作過濾器:
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);
}
在ASP.NET MVC控制器動作總是與HTTP請求相關。所以OnActionExecuting保證代碼每個請求只執行一次。如果這不是你想要的,請進一步解釋。 – 2010-11-05 17:58:42
這是事實,但不適合我。因爲在我的視圖中,我有很多Render.Action,所以當它觸及Render.Action時,BaseController.OnActionExecuting會重新運行。 – Yucel 2010-11-05 18:32:11