Asp.net MVC ReturnUrl值始终为null

时间:2017-10-08 22:11:36

标签: asp.net authentication model-view-controller login returnurl

好的我在发布之前研究并尝试了每一个建议(当然是单独的),每次都碰壁了

这是我的登录视图我使用ViewBag传递ReturnUrl值,因为我已经在许多问题的答案中看到了

   <h2>Login</h2>
@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { role = "form" }))
{
    @Html.AntiForgeryToken()


  ...............

这是登录操作结果

   [HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(UserLogin login, string returnUrl="")
{
    string message = "";
    using (NerdsContext nc = new NerdsContext())
    {
        var v = nc.User.Where(a => a.email == login.email).FirstOrDefault();
        if (v != null)
        {
            if (!v.IsEmailVerified)
            {
                ViewBag.Message = "Please verify your email first";
                return View();
            }
            if (string.Compare(Crypto.Hash(login.password), v.password) == 0)
            {
                int timeout = login.rememberMe ? 525600 : 20; // 525600 min = 1 year
                var ticket = new FormsAuthenticationTicket(login.email, login.rememberMe, timeout);
                string encrypted = FormsAuthentication.Encrypt(ticket);
                var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
                cookie.Expires = DateTime.Now.AddMinutes(timeout);
                cookie.HttpOnly = true;
                Response.Cookies.Add(cookie);

                //Redirect the user to new url
                if (Url.IsLocalUrl(returnUrl))
                {
                    ViewBag.ReturnUrl = returnUrl;
                    return Redirect(returnUrl);

                }
                else
                {
                    return RedirectToAction("Nerd", "Home");
                }
            }
            else
            {
                message = "Invalid credential provided";
            }
        }
        else
        {
            message = "Invalid credential provided";
        }
    }
    ViewBag.Message = message;
    return View();
}

最后这是我在web.config文件中添加的行

 <authentication mode="Forms">
      <forms cookieless="UseCookies"  loginUrl="/Account/Login"  timeout="30" slidingExpiration="true" protection="All"></forms>
    </authentication>

当我运行它时,我永远不会真正登录它总是将我发送回登录页面并且returnUrl的值始终为null 那么这里发生了什么????

1 个答案:

答案 0 :(得分:0)

好好经过多次搜索,我在这里找到了答案 [Request.IsAuthenticated is always false  ]

我必须在system.WebServer

中的web.config模块中添加这些行
<remove name="FormsAuthentication" />
      <add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />