Redirecting from one Action filter attribute from another

335 views Asked by At

I have two action filter attributes in my MVC app, where I am doing some work in OnActionExecuting event. And depending on a certain condition in first one, I need to execute the same block of code as the second one. So I was thinking to reuse the code.

My first question, Can I do that? then How.

Second, Is that a good approach?

UPDATE:

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
}

Thanks.

1

There are 1 answers

0
Tomasz Jaskuλa On BEST ANSWER

You can make a base class :

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

Then update you two attribute classes :

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

Then you don't need your secondary attribute because you can use directly BaseCookieAttribute on your action method.