How do I redirect user to another Controller Actio

2019-04-22 21:56发布

问题:

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.

回答1:

You can set the filterContext.Result to a RedirectToRouteResult:

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


回答2:

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?