简体   繁体   中英

Cookie expiration time not working in C#

I cannot set a persistent 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).

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.
How can I fix this ?

Update:

Added button and InsertCookie methods.

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. Only use Set when you need to update a cookie that has already been written to the response (which is pretty much never).

I get what the error is. I was trying to store data on my cookie. But I should use my cookie only for a remember me method, for example. Sorry.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM