首页 文章

C#ASP.Net MVC:RedirectFromLoginPage始终转到默认URL,而不是returnurl

提问于
浏览
9

我有一个带会员登录的MVC4应用程序(通过FormsAuthentication) .

这在web.config中定义如下 . 我的默认网址是home root(〜/):

<roleManager enabled="true" />
<authentication mode="Forms">
  <forms defaultUrl="~" loginUrl="~/Account" />
</authentication>

在Login post方法的AccountController中,以下代码是相关的 . 当用户使用有效凭据单击登录时,将执行此代码 .

if (Membership.ValidateUser(creds.Username, creds.Password))
{
    FormsAuthentication.RedirectFromLoginPage(creds.Username, false);
    return null;
}

现在,如果我(匿名)导航到:〜/ Admin,我会被重定向到〜/ Account登录,这是完美的 . 我可以看到网址形成如下:

http://localhost:23759/Account?ReturnUrl=%2fAdmin

但是,当我成功登录时,我被重定向到家(〜/)而不是〜/ Admin

请帮忙!非常感谢!

Edit: Found the actual issue: it was the post method that wasn't receiving the querystring

3 回答

  • 2

    可能是因为该路径未被检测为相同的应用程序路径:

    默认情况下,ReturnUrl变量必须引用当前应用程序中的页面 . 如果ReturnUrl引用不同应用程序或不同服务器上的页面,则RedirectFromLoginPage方法将重定向到DefaultUrl属性中的URL . 如果要允许重定向到当前应用程序之外的页面,则必须使用forms配置元素的enableCrossAppRedirects属性将EnableCrossAppRedirects属性设置为true .

    来自:http://msdn.microsoft.com/en-US/library/1f5z1yty.aspx

  • 4

    我找到了解决方案!感谢FlopScientist,他让我进一步思考 .

    确实是因为我正在做 POST method ,它没有考虑 GET 中的QueryString .

    首先我在我的视图中有这个:

    @using (Html.BeginForm("Index", "Account")
    {
        <div class="LoginBox">
        //Etc...
        </div>
    }
    

    我已将其更新为以下内容:

    @using (Html.BeginForm("Index", "Account", new { ReturnUrl = Request.QueryString["ReturnUrl"] }, FormMethod.Post))
    {
        //Etc...
    }
    

    现在我可以在调试中看到一个查询字符串,我确实得到了正确的重定向!

  • 14

    您的返回网址似乎没有任何问题:[%2f is / ] localhost:23759/Account?ReturnUrl=%2fAdmin

    那么,剩下的就是对造成这种行为的原因进行一些检查 .

    1.) 您确定返回网址中指定的返回页面:

    localhost...?ReturnUrl=%2fAdmin
    

    实际存在且您的用户有权访问它?这里Admin是一个文件夹,因此您必须在此文件夹中有一个页面 default.aspx . 如果它不存在, RedirectFromLoginPage 默认会发送给 DefaultURL .

    2.) 另外,尝试使用 FormsAuthentication.GetRedirectUrl() 方法查看会发生什么 .

    if (Membership.ValidateUser(creds.Username, creds.Password))
    {
        Response.Redirect(FormsAuthentication.GetRedirectUrl(username, false));
    }
    

    3.) 或者这有效吗? [推荐用于调试目的]

    if (!string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
    {
        Response.Redirect("~/Admin");
    }
    

    最后确保没有这样的代码行将用户重定向到其他页面/ DefaultURL .

相关问题