我有一个BaseController,其中我通过覆盖OnActionExecuting在ViewData集合中放入了一些数据。
现在,我在ChildController中有了一个不需要该视图数据的操作。
为此,我创建了一个DontPopulateViewData ActionFilterAttribute,它在BaseController上设置一个布尔值,以防止BaseController填充视图数据。
问题: ActionFilters OnActionExecuting方法在BaseController中的方法之后调用,而不是在之前调用。
在基本控制器中,总是在覆盖OnActionExecuting之前调用ActionFilters吗?有没有办法解决这个问题?
发布于 2009-05-19 20:42:20
除了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()发布于 2009-05-19 16:32:10
ActionFilterAttribute类有一个名为" order“的属性,您可以使用它来设置Action Filters的执行顺序。
在您的示例中,必须将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
注意:我没有对此进行测试。
https://stackoverflow.com/questions/882916
复制相似问题