在OnActionExecuting中重定向循环

时间:2012-02-16 15:18:03

标签: asp.net-mvc vb.net redirect

当给定条件为false时,我正试图将用户引导到我网站上的某个页面(VB,MVC4),但我一直在获得重定向循环:

Error 310 (net::ERR_TOO_MANY_REDIRECTS): There were too many redirects.

这是我的代码:

Public Class UserValidation
    Inherits ActionFilterAttribute

    Public Overrides Sub OnActionExecuting(filterContext As System.Web.Mvc.ActionExecutingContext)

        If Not DoSomeInternalCheck() Then
            filterContext.Result =
                New RedirectToRouteResult(
                    New RouteValueDictionary() From {
                        {"controller", "Home"},
                        {"action", "MessagePage"}
                    }
                )
        End If

        MyBase.OnActionExecuting(filterContext)

    End Sub

End Class

为了让用户远离网站的其余部分而只让他们看到这一页,我缺少什么?

2 个答案:

答案 0 :(得分:7)

您需要更改此过滤器,以便不会重定向用户,如果他们正在访问您要将其重定向到的主页!

重定向结果会向浏览器发送一条消息,说明“转到此其他网址”。当他们转到那个其他网址时,他们的请求会通过相同的过滤器,告诉他们“转到此网址[与之前相同的网址]”。最终,浏览器放弃并(正确地)表示您可能已经遇到某种无限重定向循环。

答案 1 :(得分:0)

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    try
    {
        base.OnActionExecuting(filterContext);

        user = (LoginViewModel)HttpContext.Current.Session["user"];
        if (user == null)
        {
           
            if (filterContext.Controller is AccountController == false)
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
                {
                    controller = "Account", 
                    action = "Login"        
                }));
            }
        }
    }
    catch (Exception)
    {
        filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
        {
            controller = "Account",
            action = "Login"
        }));
    }
}