Redirecting to specified controller and action in asp.net mvc action filter

Nick Larsen picture Nick Larsen · Sep 29, 2009 · Viewed 50.7k times · Source

I have written an action filter which detects a new session and attempts to redirect the user to a page informing them that this has happened. The only problem is I can not figure out how to make it redirect to a controller/action combo in an action filter. I can instead only figure out how to redirect to a specified url. Is there a direct way to redirect to a controller/action combo in an action filter in mvc2?

Answer

Richard Garside picture Richard Garside · Jan 19, 2011

Rather than getting a reference to HttpContent and redirecting directly in the ActionFilter you can set the Result of the filter context to be a RedirectToRouteResult. It's a bit cleaner and better for testing.

Like this:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    if(something)
    {
        filterContext.Result = new RedirectToRouteResult(
            new RouteValueDictionary {{ "Controller", "YourController" },
                                      { "Action", "YourAction" } });
    }

    base.OnActionExecuting(filterContext);
}