ASP.Net MVC Cookies不会持续存在

时间:2020-12-03 04:04:15

Essentially I'm trying to set a cookie after a user logs in to persist their username for the next time they log in. Here's my code to set the cookie. When I look at the site cookies in Firefox as soon as the cookie is set, it shows the sessionID cookie, but not the one I just set. When I check the headers in Fiddler, I don't see it setting the cookie, only my sessionID cookie.

基本上我是在用户登录后设置一个cookie,以便在他们下次登录时保留他们的用户名。这是我设置cookie的代码。当我在设置cookie后立即查看Firefox中的站点cookie时,它会显示sessionID cookie,但不会显示我刚设置的cookie。当我检查Fiddler中的标题时,我没有看到它设置cookie,只有我的sessionID cookie。

HttpCookie hc = new HttpCookie("username", model.UserName);
hc.Expires = DateTime.Now.AddYears(1);
System.Web.HttpContext.Current.Request.Cookies.Add(hc);

Here is where I check to see if the cookie exists.

这是我检查cookie是否存在的地方。

if (System.Web.HttpContext.Current.Request.Cookies["username"] != null)

Here's the full context of the methods in question

这是所讨论方法的完整背景

public ActionResult LogOn()
{
    if (System.Web.HttpContext.Current.Request.Cookies["username"] != null)
        return View(new LogOnModel { UserName = System.Web.HttpContext.Current.Request.Cookies["username"].Value });
    else
        return View();
}

[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        if (MembershipService.ValidateUser(model.UserName, model.Password))
        {
            HttpCookie hc = new HttpCookie("username", model.UserName);
            hc.Expires = DateTime.Now.AddYears(1);
            System.Web.HttpContext.Current.Request.Cookies.Add(hc);

            FormsService.SignIn(model.UserName, model.RememberMe);
            if (!String.IsNullOrEmpty(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }
        else
        {
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
        }
    }

    return View(model);
}

1 个解决方案

#1


10  

Add to response.cookies not request.cookies

添加到response.cookies not request.cookies

#1


10  

Add to response.cookies not request.cookies

添加到response.cookies not request.cookies