Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I redirect user to another Controller Action from an ASP.MVC 3 action filter?

In building a custom ASP.MVC 3 Action Filter, how should I redirect the user to another action if my test fails? I would like to pass along the original Action so that I can redirect back to the original page after the user enters the missing preference.

In controller:

[FooRequired]
public ActionResult Index()
{
    // do something that requires foo
}

in a custom filter class:

// 1. Do I need to inherit ActionFilterAttribute or implement IActionFilter?
public class FooRequired : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (TestForFoo() == false)
        {
            // 2. How do I get the current called action?

            // 3. How do I redirect to a different action,
            // and pass along current action so that I can
            // redirect back here afterwards?
        }

        // 4. Do I need to call this? (I saw this part in an example)
        base.OnActionExecuting(filterContext);            
    }
}

I'm looking for a simple ASP.MVC 3 filter example. So far my searches have lead to Ruby on Rails examples or ASP.MVC filter examples much more complicated than I need. I apologize if this has been asked before.

like image 379
Dan Sorensen Avatar asked May 05 '11 22:05

Dan Sorensen


1 Answers

Here's a small code sample using one of my own Redirect filters:

public class PrelaunchModeAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //If we're not actively directing traffic to the site...
        if (ConfigurationManager.AppSettings["PrelaunchMode"].Equals("true"))
        {
            var routeDictionary = new RouteValueDictionary {{"action", "Index"}, {"controller", "ComingSoon"}};

            filterContext.Result = new RedirectToRouteResult(routeDictionary);
        }
    }
}

If you want to intercept the route, you can get that from the ActionExecutingContext.RouteData member.

With that RouteData member, you can get the original route:

var currentRoute = filterContext.RouteData.Route;

Etc... Does that help answer your question?

like image 121
Aaronontheweb Avatar answered Oct 03 '22 01:10

Aaronontheweb