运行一次请求哪里是最好的地方?

时间:2010-11-05 17:55:05

标签: asp.net asp.net-mvc

嗨我有一些代码需要为请求运行一次。我有一个BaseController,所有控制器都派生自。我将我的代码编写到BaseController onActionExecuting方法,但它并不好,因为每个操作执行代码都在运行。我可以使用基本的if子句来预防它,但我不想那样使用它。

为请求运行代码1次的最佳位置是什么。我也希望到达HttpContext,我写这段代码。感谢

1 个答案:

答案 0 :(得分: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);
}