嗨我有一些代码需要运行一次的请求。我有一个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