Samantha J T Star
Samantha J T Star

Reputation: 32778

How can I use an action filter to redirect the output of a controller action in MVC3

I have the following in my code:

if (Session["CurrentUrl"] != null) 
{
    var ip = new Uri((string)Session["CurrentUrl"]);
    var ipNoPort = string.Format("{0}://{1}/{2}", ip.Scheme, ip.Host, ip.PathAndQuery);
    return Redirect(ipNoPort);
}

return Home();

It checks if a Session variable is set and then redirects to that URL or lets the action return to the Home method.
Does anyone have an example of how I could convert this into an action filter?
Also can I provide the action filter with the parameter of "Home" so it knows where to go to next?

Upvotes: 1

Views: 2158

Answers (1)

gdoron
gdoron

Reputation: 150253

Here is an example for ActionFilter that does redirect

public class TheFilter: ActionFilterAttribute
{
   public override void OnActionExecuted(ActionExecutedContext filterContext)
   {
       var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
       if (controllerName !="TopSecert")
            return;

       var redirectTarget = new RouteValueDictionary
                 {{"action", "ActionName"}, {"controller", "ControllerName"}};

       filterContext.Result = new RedirectToRouteResult(redirectTarget);
       // Or give a url (the last in this example):
       filterContext = new RedirectResult(filterContext.HttpContext.Request.UrlReferrer.AbsolutePath);
       // The session you can get from the context like that:
       var session = filterContext.HttpContext.Session;
   }
}

Edit: change from Executing to Executed and added session handling.

Upvotes: 5

Related Questions