在BaseController的OnActionExecuting之前调用FilterAttribute的OnActionExecuting

时间:2009-05-19 13:53:37

标签: asp.net-mvc action-filter

我有一个BaseController,其中我通过覆盖ViewDataOnActionExecuting集合中添加了一些数据。

现在我在ChildController中有一个不需要该视图数据的动作。

为此,我创建了一个DontPopulateViewData ActionFilterAttribute,它在BaseController上设置了一个bool,阻止BaseController填充viewdata。

问题:ActionFilters OnActionExecuting方法在BaseController之后而不是之前调用。

在基本控制器中覆盖OnActionExecuting之前是否总是会调用ActionFilters,有没有办法解决这个问题?

2 个答案:

答案 0 :(得分:15)

除了Marwan Aouida发布和建议的内容(在基类上使用ActionFilter)之外,我认为您无法创建在基类的OnActionExecuting()重载之前执行的ActionFilter。 。以下代码:

 [MyActionFilter(Name = "Base", Order = 2)]
 public class MyBaseController : Controller
 {
     protected override void OnActionExecuting(ActionExecutingContext filterContext)
     {
        Response.Write("MyBaseController::OnActionExecuting()<br>");
        base.OnActionExecuting(filterContext);
     }

     protected override void Execute(System.Web.Routing.RequestContext requestContext)
     {
        requestContext.HttpContext.Response.Write("MyBaseController::Execute()<br>");
        base.Execute(requestContext);
     }

    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        Response.Write("MyBaseController::OnActionExecuted()<br>");
        base.OnActionExecuted(filterContext);
    }
 }

 public class MyActionFilter : ActionFilterAttribute
 {
    public string Name;

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        filterContext.HttpContext.Response.Write("MyActionFilter_" + Name + "::OnActionExecuted()<br>");
        base.OnActionExecuted(filterContext);
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Write("MyActionFilter_" + Name + "::OnActionExecuting()<br>");
        base.OnActionExecuting(filterContext);
    }
 }

 public class MyTestController : MyBaseController
 {
     [MyActionFilter(Name = "Derived", Order = 1)]
     public void Index()
     {
        Response.Write("MyTestController::Index()<br>");
     }
 }

生成此输出:

MyBaseController::Execute()
MyBaseController::OnActionExecuting()
MyActionFilter_Derived::OnActionExecuting()
MyActionFilter_Base::OnActionExecuting()
MyTestController::Index()
MyActionFilter_Base::OnActionExecuted()
MyActionFilter_Derived::OnActionExecuted()
MyBaseController::OnActionExecuted()

答案 1 :(得分:0)

ActionFilterAttribute类有一个名为“Order”的属性,您可以使用该属性设置执行操作过滤器的顺序。
在您的情况下,您必须将BaseController中的Filter属性的顺序设置为2,将DerivedController中的Filter属性的顺序设置为1:

[MyFilter(Order=2)]
public class BaseController:Controller
{

  public ActionResult MyAction() {

  }

}

[MySecondFilter(Order=1)]
public class DerivedController:BaseController
{

  public ActionResult AnotherAction() {

  }

}

阅读此内容以获取更多信息:http://msdn.microsoft.com/en-us/library/dd381609.aspx

注意:我没有测试过这个。