在asp.net mvc动作过滤器中重定向到指定的控制器和操作

时间:2009-09-29 03:11:48

标签: asp.net-mvc redirect action-filter

我编写了一个动作过滤器,用于检测新会话,并尝试将用户重定向到一个页面,通知他们发生了这种情况。唯一的问题是我无法弄清楚如何将其重定向到动作过滤器中的控制器/动作组合。我只能弄清楚如何重定向到指定的网址。是否有直接方法在mvc2中的动作过滤器中重定向到控制器/动作组合?

3 个答案:

答案 0 :(得分:90)

您可以将过滤器上下文的Result设置为RedirectToRouteResult,而不是直接在ActionFilter中获取对HttpContent的引用和重定向。它更清洁,更适合测试。

像这样:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    if(something)
    {
        filterContext.Result = new RedirectToRouteResult(
            new RouteValueDictionary {{ "Controller", "YourController" },
                                      { "Action", "YourAction" } });
    }

    base.OnActionExecuting(filterContext);
}

答案 1 :(得分:17)

编辑:最初的问题是关于如何检测会话注销,然后自动重定向到指定的控制器和操作。事实证明这个问题更有用,因为它是目前的形式。


我最终使用了一系列项目来实现这一目标。

首先是找到的会话过期过滤器here。然后我想要指定控制器/动作组合以获得重定向URL,我发现了很多here的例子。最后我想出了这个:

public class SessionExpireFilterAttribute : ActionFilterAttribute
{
    public String RedirectController { get; set; }
    public String RedirectAction { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpContext ctx = HttpContext.Current;

        if (ctx.Session != null)
        {
            if (ctx.Session.IsNewSession)
            {
                string sessionCookie = ctx.Request.Headers["Cookie"];
                if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0))
                {
                    UrlHelper helper = new UrlHelper(filterContext.RequestContext);
                    String url = helper.Action(this.RedirectAction, this.RedirectController);
                    ctx.Response.Redirect(url);
                }
            }
        }

        base.OnActionExecuting(filterContext);
    }
}

答案 2 :(得分:5)

使用RedirectToAction致电this overload

protected internal RedirectToRouteResult RedirectToAction(
    string actionName,
    RouteValueDictionary routeValues
)

在Action Filters中,故事有点不同。举个好例子,请看这里:

http://www.dotnetspider.com/resources/29440-ASP-NET-MVC-Action-filters.aspx

相关问题