2010-11-05 46 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

相关问题