Cookie过期时间不适用于C#
问题描述:
我无法设置持久cookie。它只成为会话。Cookie过期时间不适用于C#
我知道同样的问题已经问here但我无法修复它,即使我做了所有的步骤。
(不能用提琴手测试)。
我的代码是:
/// 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 "";
}
}
我使用Chrome。
我该如何解决这个问题?
更新:
添加了按钮和InsertCookie方法。
答
我得到了什么错误。 我正试图在我的cookie上存储数据。 但是,例如,我应该只使用我的cookie来记住我的方法。 对不起。
答
而不是
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 void CreateCookie(string Cookie)
{
HttpCookie cookie = new HttpCookie(Cookie);
cookie.Expires = DateTime.Now.AddYears(1);
HttpContext.Current.Response.Cookies.Add(cookie); //<-- Add
}