在asp.net mvc 动作过滤器中重定向到指定的控制器和动作 [英] Redirecting to specified controller and action in asp.net mvc action filter
问题描述
我编写了一个动作过滤器,它检测新会话并尝试将用户重定向到一个页面,通知他们发生了这种情况.唯一的问题是我不知道如何让它重定向到动作过滤器中的控制器/动作组合.我只能弄清楚如何重定向到指定的 url.有没有直接的方法可以重定向到 mvc2 中动作过滤器中的控制器/动作组合?
I have written an action filter which detects a new session and attempts to redirect the user to a page informing them that this has happened. The only problem is I can not figure out how to make it redirect to a controller/action combo in an action filter. I can instead only figure out how to redirect to a specified url. Is there a direct way to redirect to a controller/action combo in an action filter in mvc2?
推荐答案
您可以将过滤器上下文的 Result 设置为 RedirectToRouteResult,而不是获取对 HttpContent 的引用并直接在 ActionFilter 中重定向.它更简洁,更适合测试.
Rather than getting a reference to HttpContent and redirecting directly in the ActionFilter you can set the Result of the filter context to be a RedirectToRouteResult. It's a bit cleaner and better for testing.
像这样:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if(something)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary {{ "Controller", "YourController" },
{ "Action", "YourAction" } });
}
base.OnActionExecuting(filterContext);
}
这篇关于在asp.net mvc 动作过滤器中重定向到指定的控制器和动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!