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

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

Leave a Comment