如何在asp.net中创建持久性cookie?

Vik*_*kas 69 asp.net cookies

我正在创建以下行的cookie:

HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires.AddYears(1);
Response.Cookies.Add(userid);
Run Code Online (Sandbox Code Playgroud)

现在如何让它持久?

因为如果我在关闭浏览器后再次访问同一页面,我将无法取回它.

thi*_*eek 96

这是你如何做到这一点.

编写持久性cookie.

//create a cookie
HttpCookie myCookie = new HttpCookie("myCookie");

//Add key-values in the cookie
myCookie.Values.Add("userid", objUser.id.ToString());

//set cookie expiry date-time. Made it to last for next 12 hours.
myCookie.Expires = DateTime.Now.AddHours(12);

//Most important, write the cookie to client.
Response.Cookies.Add(myCookie);
Run Code Online (Sandbox Code Playgroud)

读取持久性cookie.

//Assuming user comes back after several hours. several < 12.
//Read the cookie from Request.
HttpCookie myCookie = Request.Cookies["myCookie"];
if (myCookie == null)
{
    //No cookie found or cookie expired.
    //Handle the situation here, Redirect the user or simply return;
}

//ok - cookie is found.
//Gracefully check if the cookie has the key-value as expected.
if (!string.IsNullOrEmpty(myCookie.Values["userid"]))
{
    string userId = myCookie.Values["userid"].ToString();
    //Yes userId is found. Mission accomplished.
}
Run Code Online (Sandbox Code Playgroud)

  • 您的代码在功能上与原始问题中的代码没有什么不同,但您的cookie在12小时内到期,OP在一年内到期. (5认同)
  • 读取持久性cookie代码对我不起作用.请参阅这篇文章中的答案. (3认同)
  • @Ortund 正如 [Chance](/sf/answers/2174156351/) 指出的那样,有一个关键区别,OP 正在添加到 0001/01/01 的默认时间,而这个答案正在添加到当前时间。 (3认同)

小智 44

虽然接受的答案是正确的,但它没有说明原始代码无法工作的原因.

你的问题代码不好:

HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires.AddYears(1);
Response.Cookies.Add(userid);
Run Code Online (Sandbox Code Playgroud)

看看第二行.到期的基础是Expires属性,其中包含默认值1/1/0001.上面的代码正在评估为1/1/0002.此外,评估不会被保存回酒店.而应该使用当前日期的基础设置Expires属性.

更正代码:

HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(userid);
Run Code Online (Sandbox Code Playgroud)


Chr*_*sic 26

在未加密的cookie中存储像userid这样的东西时,FWIW要非常小心.这样做会使您的网站非常容易发生cookie中毒,用户可以轻松冒充其他用户.如果您正在考虑这样的事情,我强烈建议您直接使用表单身份验证cookie.

bool persist = true;

var cookie = FormsAuthentication.GetAuthCookie(loginUser.ContactId, persist);

cookie.Expires = DateTime.Now.AddMonths(3);

var ticket = FormsAuthentication.Decrypt(cookie.Value);

var userData = "store any string values you want inside the ticket
                 extra than user id that will be encrypted"

var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name,
     ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData);

cookie.Value = FormsAuthentication.Encrypt(newTicket);

Response.Cookies.Add(cookie);
Run Code Online (Sandbox Code Playgroud)

然后,您可以随时从ASP.NET页面中读取此内容

string userId = null;
if (this.Context.User.Identity.IsAuthenticated) 
{
    userId = this.Context.User.Identity.Name;
}
Run Code Online (Sandbox Code Playgroud)

  • 因为变量的冗余规范是多余的.由于问题专门将userid显示为存储在cookie中的值,因此FormsAuth cookie是此IMO最正确的解决方案. (15认同)