Search code examples
c#asp.netcookiesstatic-classes

issues in c# static class to deal with cookies


I want to create a static class that will deal with the cookies in my ASP.NET site. The class is written in c# and sits in App_code folder.

The issue I have is that all the time, the updates in the cookie delete my previous value in the cookie, and not been added. I created a simple code.

enter image description here

At first the cookie has the value 1=a , and this is good (correct). But in the second run, when I enter the if and not the else, the cookie value is 2=b.

enter image description here

the result that I want is 1=a&2=b

Thank you


Solution

  • Let me try and explain what's going on. When you set the value of the cookie collection "test2" like this HttpContext.Current.Response.Cookies["test2"].Values.Add("1", "a"); you are sending a new cookie collection object as part of a new HTTP Response stream. The new HTTP Response object does not know anything about the previously set Name/Value cookie item (which now can be accessed via the HTTP's Request object). To resolve this, simply add the cookie in the request object to the new cookie collection in the Response object.

    
    
        if (Request.Cookies["stackoverflow"] != null)
        {               
            Response.Cookies["stackoverflow"].Values.Add(Request.Cookies["stackoverflow"].Values);
            Response.Cookies["stackoverflow"].Values.Add("2", "bbbb");
        }
        else
        {
            Response.Cookies["stackoverflow"]["1"] = "aaaaaa";
        }