【发布时间】:2011-03-09 14:15:47
【问题描述】:
我正在使用以下几行创建 cookie:
HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires.AddYears(1);
Response.Cookies.Add(userid);
现在我怎样才能让它持久化?
如果我在关闭浏览器后再次访问同一页面,我将无法恢复。
【问题讨论】:
我正在使用以下几行创建 cookie:
HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires.AddYears(1);
Response.Cookies.Add(userid);
现在我怎样才能让它持久化?
如果我在关闭浏览器后再次访问同一页面,我将无法恢复。
【问题讨论】:
您需要将此添加为最后一行...
HttpContext.Current.Response.Cookies.Add(userid);
当你需要读取 cookie 的值时,你会使用类似这样的方法:
string cookieUserID= String.Empty;
try
{
if (HttpContext.Current.Request.Cookies["userid"] != null)
{
cookieUserID = HttpContext.Current.Request.Cookies["userid"];
}
}
catch (Exception ex)
{
//handle error
}
return cookieUserID;
【讨论】:
您可以这样做。
写入持久性 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);
读取持久性 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.
}
【讨论】:
FWIW 在未加密的 cookie 中存储用户 ID 之类的内容时要非常小心。这样做会使您的网站很容易出现 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);
然后您可以随时从 ASP.NET 页面读取此内容
string userId = null;
if (this.Context.User.Identity.IsAuthenticated)
{
userId = this.Context.User.Identity.Name;
}
【讨论】:
var。
//添加cookie
var panelIdCookie = new HttpCookie("panelIdCookie");
panelIdCookie.Values.Add("panelId", panelId.ToString(CultureInfo.InvariantCulture));
panelIdCookie.Expires = DateTime.Now.AddMonths(2);
Response.Cookies.Add(panelIdCookie);
//读取cookie
var httpCookie = Request.Cookies["panelIdCookie"];
if (httpCookie != null)
{
panelId = Convert.ToInt32(httpCookie["panelId"]);
}
【讨论】:
虽然接受的答案是正确的,但它没有说明为什么原始代码无法工作。
您的问题中的错误代码:
HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires.AddYears(1);
Response.Cookies.Add(userid);
看看第二行。到期的基础是 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);
【讨论】:
据我了解,您使用 ASP.NET 身份验证并设置 cookie 持久性,您需要设置 FormsAuthenticationTicket.IsPersistent = true 这是主要思想。
bool isPersisted = true;
var authTicket = new FormsAuthenticationTicket(
1,
user_name,
DateTime.Now,
DateTime.Now.AddYears(1),//Expiration (you can set it to 1 year)
isPersisted,//THIS IS THE MAIN FLAG
addition_data);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, authTicket );
if (isPersisted)
authCookie.Expires = authTicket.Expiration;
HttpContext.Current.Response.Cookies.Add(authCookie);
【讨论】: