在构建自定义ASP.MVC 3动作过滤器时,如果我的测试失败,应该如何将用户重定向到另一个动作?我想传递原始操作,以便在用户输入缺少的首选项后我可以重定向回原始页面。
在控制器中:
[FooRequired]
public ActionResult Index()
{
// do something that requires foo
}
在自定义过滤器类中:
// 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);
}
}
我正在寻找一个简单的ASP.MVC 3过滤器示例。到目前为止,我的搜索导致Ruby on Rails示例或ASP.MVC过滤器示例比我需要的要复杂得多。如果之前有人问我,我会道歉。
答案 0 :(得分: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);
}
}
}
如果您想截取路线,可以从ActionExecutingContext.RouteData member获取。
使用该RouteData成员,您可以获得原始路线:
var currentRoute = filterContext.RouteData.Route;
等......这有助于回答你的问题吗?
答案 1 :(得分:6)
您可以将filterContext.Result
设置为RedirectToRouteResult
:
filterContext.Result = new RedirectToRouteResult(...);