1

I'm trying to work out how to re-use some code in my MVC controller actions. I want to redirect to another page if a status of something is set. I've written a method to do this but it seems as if I'd have to paste this across every controller action e.g.

[HttpGet]        
public virtual ActionResult DoThis(Guid id)

    ActionResult result;
    if (checkRedirect(out result))
    {
            return result;
    }

   //otherwise continue

I thought I might be able to do this using an Action Filter but then I have to set up property injection in the filter in order to check my status which I want to avoid. There must be a common way of doing this that I'm missing...?

1
  • 1
    Action filters are the right approach. If you can guarantee that the property will always have a constant name, then you can simply look for that single property in the filter and check if it exists. If the name will vary per action, then have the attribute take in the property name as a parameter. Commented Mar 19, 2015 at 17:09

1 Answer 1

2

Way 1:

Make a base controller and inherit other controllers from it:

public class DefaultController : Controller
{
   protected override void OnActionExecuting(ActionExecutingContext filterContext)
   {
       ActionResult result;
       if (checkRedirect(out result))        
       {
           filterContext.Result = result; // redirect
       }

    }
}

and in your controller:

public class SomeController : DefaultController
{
  [HttpGet]        
  public virtual ActionResult DoThis(Gud)
  {
     // do something here which you were putting in else part
  }
}

Way 2:

or create action filter attribute:

public class MyCustomAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {

       ActionResult result;
       if (checkRedirect(out result))        
       {
           filterContext.Result = result; // redirect
       }

    }

}

and put it on your action:

 public class SomeController : Controller
 {
  [HttpGet]
  [MyCustom]        
  public virtual ActionResult DoThis(Gud)
  {
      // do something here which you were putting in else part
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I would like to do Way 2 but doing the DI on the Filter seems a bit of a fiddle. I think I'll use Way 1 for now, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.