微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/aspnet/245138.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐