【问题标题】:Redirecting from one Action filter attribute from another从另一个动作过滤器属性重定向
【发布时间】:2013-12-02 19:16:51
【问题描述】:

我的 MVC 应用程序中有两个动作过滤器属性,我在 OnActionExecuting 事件中做一些工作。并且根据第一个中的特定条件,我需要执行与第二个相同的代码块。所以我想重用代码。

我的第一个问题,我可以这样做吗?然后怎么做。

第二,这是一个好方法吗?

更新:

public class Primary : ActionFilterAttribute{
   public override void OnActionExecuting(ActionExecutingContext filterContext){
      if(there is no cookie){
          // Code
      }
      else{
          // Execute the same code block as Secondary OnActionExecuting
      }
   }
}

public class Secondary : ActionFilterAttribute{
   public override void OnActionExecuting(ActionExecutingContext filterContext){
       // Access cookie and do other work
   }
}

[Primary]
public ActionResult MyPrimaryAction(Guid id){
    // Do work
}

[Secondary]
public ActionResult MySecondaryAction(Guid id){
    // Do work
}

谢谢。

【问题讨论】:

  • 你能发布一个你做了什么的代码示例吗?因为不清楚。
  • @Thomas 感谢您的回复。用代码块更新。

标签: asp.net-mvc-4 actionfilterattribute


【解决方案1】:

你可以创建一个基类:

public class BaseCookieAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext){
       // Access cookie and do other work
   }
}

然后更新你两个属性类:

public class Primary : BaseCookieAttribute {
   public override void OnActionExecuting(ActionExecutingContext filterContext){
      if(there is no cookie){
          // Code
      }
      else{
          base.OnActionExecuting(filterContext);
      }
   }
}

那么你就不需要你的次要属性了,因为你可以在你的操作方法上直接使用BaseCookieAttribute。

【讨论】:

    猜你喜欢
    • 2011-07-24
    • 2010-10-07
    • 2016-11-21
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 2015-02-11
    • 2014-04-26
    • 1970-01-01
    相关资源
    最近更新 更多