【问题标题】:mvc forms authentication redirectingmvc 表单身份验证重定向
【发布时间】:2012-09-27 12:51:18
【问题描述】:

我正在尝试向 mvc 站点添加表单身份验证,当我运行应用程序时,我被重定向到登录页面(这是正确的)。但是,每次我尝试登录时,页面都会被刷新,而控制器永远不会收到发布请求。我认为我的表单身份验证已关闭并将所有请求重定向回登录页面?任何帮助将不胜感激!

以下是我的网络配置信息:

<authentication mode="Forms">
      <forms loginUrl="~/Account" timeout="30" slidingExpiration="false" requireSSL="false" />      
    </authentication>
<authorization>
      <deny users ="?" />
      <allow users = "*" />
    </authorization>

下面是我的登录页面:

@using (Html.BeginForm("Login", "Account", FormMethod.Post))
{
    @Html.LabelFor(x => x.Username)<br />
    @Html.TextBoxFor(x => x.Username)

    <br />
    <br />

    @Html.LabelFor(x => x.Password)<br />
    @Html.TextBoxFor(x => x.Password)


    <br />
    <br />
    <br />

    <input type="submit" value="Login" />
}

下面是我的控制器:

[HttpGet]
        public ActionResult Index()
        {
            return View("~/Views/Account/Login.cshtml", new LoginViewModel());
        }

        [HttpPost]
        public ActionResult Login(LoginViewModel viewModel)
        {
            Membership.ValidateUser(viewModel.Username, viewModel.Password);
            FormsAuthentication.SetAuthCookie(viewModel.Username, viewModel.RememberMe);

            return View("~/Views/Account/Login.cshtml", viewModel);
        }

【问题讨论】:

    标签: c# asp.net-mvc forms-authentication


    【解决方案1】:

    我相信POST 正在发生,但我的朋友遇到的问题是您重定向到POST 末尾的登录页面。

    return View("~/Views/Account/Login.cshtml", viewModel);
    

    将用户引导至主页。

    【讨论】:

    • @user587950,很高兴我能提供帮助,请将其标记为我自己和社区的答案!
    【解决方案2】:

    其他人建议从您的 Login HttpPost 操作重定向到主页,但由 Visual Studio 创建的标准 MVC“Intranet 应用程序”模板尝试重定向到 returnUrl,该 returnUrl 作为 FormsAuthentication 作为查询字符串传递给 Login 操作基础设施:

    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
    {
        return Redirect(returnUrl);
    }
    else
    {
        return RedirectToAction("Index", "Home");
    }
    

    除非您有充分的理由不这样做,否则我会复制此内容。

    【讨论】:

      【解决方案3】:

      没错。 因为那个代码:

      public ActionResult Index()
      {
         return View("~/Views/Account/Login.cshtml", new LoginViewModel());
      }
      

      改成return View(); 并在相应的文件夹中创建名为 Index 的视图。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-04-20
        • 1970-01-01
        • 2023-03-22
        • 1970-01-01
        • 2013-02-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多