asp.net-mvc – 在BaseController的OnActionExecuting之前调用FilterAttribute的OnActionExecuting

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 在BaseController的OnActionExecuting之前调用FilterAttribute的OnActionExecuting前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个BaseController,我在其中通过重写OnActionExecuting在ViewData集合中放入一些数据.

现在我在ChildController中有一个不需要该视图数据的Action.

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

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

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

解决方法

除了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()
原文链接:https://www.f2er.com/aspnet/246711.html

猜你在找的asp.Net相关文章