Mark Dixon Tech
Mark Dixon Tech

Reputation: 91

Implementing Common Redirect Code in MVC

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...?

Upvotes: 1

Views: 86

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

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
  }
}

Upvotes: 2

Related Questions