asp.net mvc身份验证操作没有获得returnUrl

Max*_*xim 1 asp.net-mvc asp.net-mvc-2

在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();
}
Run Code Online (Sandbox Code Playgroud)

但是当通过动作处理请求时,returnUrl参数为null,但是应该有作者所说的值.有人可以解释一下吗?

我发送请求的表单如下所示: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>
Run Code Online (Sandbox Code Playgroud)

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

验证:

<authentication mode="Forms">
  <forms loginUrl="~/Admin/LogOn" timeout="2880">
    <credentials passwordFormat="SHA1">
      <user name="admin" password="hashedPassword"/>
    </credentials>
  </forms>
</authentication>
Run Code Online (Sandbox Code Playgroud)

Rem*_*mus 6

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

<form>在视图中的当前标记不会考虑这一点.它始终采用相同的操作,而忽略任何现有的QueryString值.

如果您使用:

<% using (Html.BeginForm()) { %>
   // enter form html without the <form> tag
<% } %>
Run Code Online (Sandbox Code Playgroud)

这将自动创建一个<form>带有"操作"值的标记,该值会考虑页面上已存在的任何查询字符串.