Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC - Redirect inside the Constructor

I would like to know how am I able to redirect the request inside the controller constructor if I need to do it?.

For example: Inside the constructor I need to initialize an object with an dynamic value, in some cases I don't want to do it and in that case I want to redirect to some other place. At the same way the rest of the constructor will not be executed neither the "original following action".

How can I do it? Thank you

EDIT #1

Initially I used:

  public override void OnActionExecuting(ActionExecutingContext filterContext) 

There I could redirect to some other controller/action/url, but later in time, I needed to change my controller, where I initialize an variable in his constructor and have some code that really needs to redirect the request :P

I need this also because the OnActionExecuting executes AFTER the controller constructor. And in my logic, the redirect needs to be done there.

like image 447
Dryadwoods Avatar asked Jan 25 '11 12:01

Dryadwoods


1 Answers

Performing redirects inside the controller constructor is not a good practice because the context might not be initialized. The standard practice is to write a custom action attribute and override the OnActionExecuting method and perform the redirect inside. Example:

public class RedirectingActionAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        if (someConditionIsMet)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
            {
                controller = "someOther",
                action = "someAction"
            }));
        }
    }
}

and then decorate the controller which you would like to redirect with this attribute. Be extremely careful not to decorate the controller you are redirecting to with this attribute or you are going to run into an endless loop.

So you could:

[RedirectingAction]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        // This action is never going to execute if the 
        // redirecting condition is met
        return View();
    }
}

public class SomeOtherController : Controller
{
    public ActionResult SomeAction()
    {
        return View();
    }
}
like image 109
Darin Dimitrov Avatar answered Nov 15 '22 14:11

Darin Dimitrov