【问题标题】:Redirecting to specified controller and action in asp.net mvc action filter重定向到asp.net mvc动作过滤器中的指定控制器和动作
【发布时间】:2010-12-02 04:50:53
【问题描述】:

我编写了一个动作过滤器,它检测新会话并尝试将用户重定向到一个页面,通知他们这已经发生。唯一的问题是我无法弄清楚如何让它重定向到动作过滤器中的控制器/动作组合。相反,我只能弄清楚如何重定向到指定的 url。有没有直接的方法来重定向到 mvc2 中动作过滤器中的控制器/动作组合?

【问题讨论】:

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


    【解决方案1】:

    您可以将过滤器上下文的 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);
    }
    

    【讨论】:

    • 我头疼,现在不疼了。谢谢
    • 如何将数据传递给“YourAction”?
    【解决方案2】:

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


    我最终使用了多个项目的组合来实现这个目标。

    首先是找到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);
        }
    }
    

    【讨论】:

    • 如果你想让这个更可测试,我相信你可以简单地将filterContext.Result设置为RedirectResult,而不是显式重定向。最终结果是 MVC 仍将执行重定向,但这样您就可以编写手动调用 OnActionExecuting() 的单元测试,然后针对 filterContext.Result 进行断言。
    【解决方案3】:

    使用this overload调用RedirectToAction

    protected internal RedirectToRouteResult RedirectToAction(
        string actionName,
        RouteValueDictionary routeValues
    )
    

    在动作过滤器中,故事有点不同。一个很好的例子,看这里:

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

    【讨论】:

    • 这是在动作过滤器 (+1) 中寻找重定向的好地方,但我真的想为我的过滤器指定控制器/动作组合。在自定义路由的情况下,我也不想仅仅连接字符串,但我最终找到了一些可以提供帮助的东西。看我的回答。
    猜你喜欢
    • 2016-10-06
    • 1970-01-01
    • 2014-12-25
    • 2016-11-21
    • 2015-04-15
    • 2018-06-11
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    相关资源
    最近更新 更多