-1

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

mmushtaq
  • 3,430
  • 7
  • 30
  • 47
Alon Galpe
  • 55
  • 3
  • 10
  • 4
    If you want help from this site, please post your code. Not images of your code because; 1. we cannot grab your code from an image to put it in a test harness to try it out. 2. Absolutely no one will take the time to retype your code from an image to help you out. Do yourself a favor and put the actual code/snippets in the post. – Kevin Sep 22 '16 at 18:25
  • I second @Kevin comment. – garfbradaz Sep 22 '16 at 20:22

1 Answers1

0

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";
    }

DragoRaptor
  • 735
  • 5
  • 10
  • Thank you for the answer, but the problem is that the request and response cookies are not available at c# file (c# class, not asp.net page). that is the reason I used HttpConext which is available in c# file. I am looking for another solution that is available in c# file. – Alon Galpe Sep 23 '16 at 02:03
  • This is C#. You could either use HTTPContext.Current or the shorter Request.Cookies like in the example above. Just make sure you have the Sytem.Web and other namespaces in the using statement. In your example the 'test2' cookie collection is reset on each response. Make sure you set the old values before adding new values to the test2 cookie collection. – DragoRaptor Sep 23 '16 at 16:44