簡體   English   中英

Cookie過期時間在C#中不起作用

[英]Cookie expiration time not working in C#

我無法設置永久性Cookie。 它僅成為會話。

我知道在這里問過同樣的問題但是即使我做了所有步驟,也無法解決。
(無法與Fiddler進行測試)。

我的代碼是:

/// 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。
我怎樣才能解決這個問題 ?

更新:

添加了button和InsertCookie方法。

代替

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
}

使用“ Add添加cookie。 僅在需要更新已經寫入響應中的cookie時才使用Set (幾乎從來沒有)。

我得到了錯誤所在。 我試圖將數據存儲在Cookie上。 但是,例如,我應該僅將cookie用於“記住我”方法。 抱歉。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM