Yuc*_*cel 2 asp.net asp.net-mvc
嗨我有一些代码需要运行一次请求.我有一个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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用此自定义属性装饰您的基本控制器.如果您更喜欢它而不是操作属性,可以在基础控制器的重写的OnActionExecuting方法中执行类似的测试:
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.IsChildAction)
{
// this is not the a child action => do the processing
}
base.OnActionExecuting(filterContext);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1082 次 |
| 最近记录: |