[英]Cookie expiration time not working in C#
I cannot set a persistent cookie. 我无法设置永久性Cookie。 It become session only. 它仅成为会话。
I know the same problem have asked here but I couldn't fix it even I did all the steps. 我知道在这里问过同样的问题,但是即使我做了所有步骤,也无法解决。
(Couldn't have test with Fiddler). (无法与Fiddler进行测试)。
My code is: 我的代码是:
/// Default.aspx.cs methods :
protected void Page_Load(object sender, EventArgs e)
{
if (! Cookies.CookieExist("kuki"))
{
Cookies.CreateCookie("kuki");
}
Fill();
}
private void Fill()
{
string a = Cookies.GetCookieValue("kuki", "key");
if (!a.Contains("data"))
{
return;
}
// codes for a
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
if (TextBox1.Text != string.Empty)
{
Cookies.InsertCookie("kuki", "key", TextBox1.Text);
}
}
/// Cookie class methods:
public static void InsertCookie(string Cookie, string Key, string Data)
{
HttpCookie Kuki = HttpContext.Current.Request.Cookies[Cookie];
Kuki[Key] = Data;
HttpContext.Current.Response.SetCookie(Kuki);
}
public static bool CookieExist(string Cookie)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[Cookie];
if (cookie == null)
{
return false;
}
else
{
return true;
}
}
public static void CreateCookie(string Cookie)
{
HttpCookie cookie = new HttpCookie(Cookie);
cookie.Expires = DateTime.Now.AddYears(1);
HttpContext.Current.Response.Cookies.Set(cookie);
}
public static string GetCookieValue(string CookieName, string CookieKey)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[CookieName];
try
{
if (cookie != null)
{
return cookie[CookieKey].ToString();
}
else
{
return "";
}
}
catch (Exception)
{
return "";
}
}
I use Chrome. 我使用Chrome。
How can I fix this ? 我怎样才能解决这个问题 ?
Update: 更新:
Added button and InsertCookie methods. 添加了button和InsertCookie方法。
Instead of 代替
public static void CreateCookie(string Cookie)
{
HttpCookie cookie = new HttpCookie(Cookie);
cookie.Expires = DateTime.Now.AddYears(1);
HttpContext.Current.Response.Cookies.Set(cookie);
}
Try 尝试
public static void CreateCookie(string Cookie)
{
HttpCookie cookie = new HttpCookie(Cookie);
cookie.Expires = DateTime.Now.AddYears(1);
HttpContext.Current.Response.Cookies.Add(cookie); //<-- Add
}
Use Add
to add a cookie. 使用“ Add
添加cookie。 Only use Set
when you need to update a cookie that has already been written to the response (which is pretty much never). 仅在需要更新已经写入响应中的cookie时才使用Set
(几乎从来没有)。
I get what the error is. 我得到了错误所在。 I was trying to store data on my cookie. 我试图将数据存储在Cookie上。 But I should use my cookie only for a remember me method, for example. 但是,例如,我应该仅将cookie用于“记住我”方法。 Sorry. 抱歉。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.