我正在创建以下行的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)
小智 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)
归档时间: |
|
查看次数: |
97854 次 |
最近记录: |