【问题标题】:asp.net mvc authentication action doesn't get returnUrlasp.net mvc 身份验证操作没有得到 returnUrl
【发布时间】:2010-11-10 19:37:01
【问题描述】:

在 asp.net/mvc 身份验证的经典示例中,LogOn 操作获取 LogOnViewModel 和 returnUrl 字符串以进行身份​​验证并重定向到以前的 Url。

[HttpPost]
public ActionResult LogOn(LogOnViewModel model, string returnUrl)
{
if (ModelState.IsValid)
    if (!FormsAuthentication.Authenticate(model.UserName, model.Password))                                              
        ModelState.AddModelError("", "Incorrect user name or password."); 

    if (ModelState.IsValid)
    {
        FormsAuthentication.SetAuthCookie(model.UserName, false);
        return Redirect(returnUrl ?? "Bookings");
    }
    else
        return View();
}

但是当请求由动作处理时,returnUrl 参数为空,但是应该有一个值,正如作者所说。有人可以解释一下吗?

我发送请求的表单如下所示:Views/Admin/LogOn.aspx

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
  <div id="login">
    <% Html.EnableClientValidation(); %>
    <% using (Html.BeginForm("LogOn", "Admin")) { %>
      <%= Html.ValidationSummary(true) %>
      <div><label>Username:</label><input name="userName" type="text" /></div>
      <div><label>Password:</label><input name="password" type="password" /></div>
      <div><input type="submit" value="Login" /></div>
    <% } %>
  </div>
</asp:Content>

表单上没有生成隐藏字段。

身份验证:

<authentication mode="Forms">
  <forms loginUrl="~/Admin/LogOn" timeout="2880">
    <credentials passwordFormat="SHA1">
      <user name="admin" password="hashedPassword"/>
    </credentials>
  </forms>
</authentication>

【问题讨论】:

  • 您的提交表单是什么样的?如果您使用POST 请求提交,您是否有returnUrl 参数的隐藏元素?

标签: asp.net-mvc asp.net-mvc-2


【解决方案1】:

当您转到未经身份验证的页面时,当您被 MVC 框架重定向到登录页面时,ReturnURL 参数会自动添加到您的查询字符串中。

您当前在视图中的&lt;form&gt; 标记没有考虑到这一点。无论任何现有的 QueryString 值,它总是执行相同的操作。

如果你使用:

<% using (Html.BeginForm()) { %>
   // enter form html without the <form> tag
<% } %>

这将自动创建一个带有“action”值的&lt;form&gt; 标记,该标记会考虑您页面上已存在的任何查询字符串。

【讨论】:

  • 用户想要调用的操作 (www.mysite.com/Admin/Index) 具有 [Authorize] 属性,这就是他被重定向到登录页面的原因。登录时的 URL 看起来像 www.mysite.com/Admin/LogOn?ReturnUrl=%2fAdmin%2findex /// 使用 (Html.BeginForm()) 没有解决问题,returnUrl 中仍然为空
  • hmm,检查你的变量是不是合适的大小写:ReturnUrl
  • 试过了,没用。 Request.QueryString 为空。它闻起来很腥,它应该工作。这些请求的路由 routes.MapRoute( "AdminMainPage", "admin/{action}", new { controller = "Admin", action = "Index" } ); routes.MapRoute("AdminLogOn", "admin/logon/", new { controller = "Admin", action = "LogOn" });无论如何,非常感谢
  • 是的,这有点远 - 你能用 web.config 中的身份验证设置和你视图中的新代码更新你的问题吗?
  • 没有问题 - 为什么它不工作让我很烦恼。我猜 Html.BeginForm(string, string) 方法不携带任何 QueryString 转发,我想这是有道理的,因为有一个 Html.BeginForm(string, string, object) 重载来指定 QueryString 参数。
【解决方案2】:

也许尝试在表单中包含一个隐藏的输入元素:

<%:Html.Hidden("returnUrl", yourUrlHere) %>

【讨论】:

  • 我不知道用户是从哪个页面重定向到登录页面的。有什么办法知道吗?
  • 查看 Remus 的评论,它是自动添加的。无需添加隐藏的输入元素。
猜你喜欢
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 2010-09-24
  • 2016-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-10
相关资源
最近更新 更多