如何从ASP.MVC 3动作过滤器将用户重定向到另一个Controller Action?

Dan*_*sen 8 asp.net-mvc asp.net-mvc-3

在构建自定义ASP.MVC 3动作过滤器时,如果我的测试失败,应该如何将用户重定向到另一个动作?我想传递原始Action,以便在用户输入缺少的首选项后我可以重定向回原始页面.

在控制器中:

[FooRequired]
public ActionResult Index()
{
    // do something that requires foo
}
Run Code Online (Sandbox Code Playgroud)

在自定义筛选器类中:

// 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);            
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在寻找一个简单的ASP.MVC 3过滤器示例.到目前为止,我的搜索导致Ruby on Rails示例或ASP.MVC过滤器示例比我需要的要复杂得多.如果以前曾经问过我,我道歉.

Aar*_*web 8

这是使用我自己的Redirect过滤器之一的小代码示例:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果要拦截路由,可以从ActionExecutingContext.RouteData成员获取该路由.

使用该RouteData成员,您可以获得原始路线:

var currentRoute = filterContext.RouteData.Route;
Run Code Online (Sandbox Code Playgroud)

等等......这有助于回答您的问题吗?


Sha*_*ade 6

您可以设置filterContext.ResultRedirectToRouteResult:

filterContext.Result = new RedirectToRouteResult(...);
Run Code Online (Sandbox Code Playgroud)