ASP.Net MVC Cookies不会持续存在

前端之家收集整理的这篇文章主要介绍了ASP.Net MVC Cookies不会持续存在前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
基本上我是在用户登录后设置一个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);

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

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

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

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);
}

解决方法

添加到response.cookies not request.cookies
原文链接:https://www.f2er.com/aspnet/245138.html

猜你在找的asp.Net相关文章