Pete
Pete

Reputation: 58432

C# multi-value cookies not working

Hi I am creating a cookie in the following way:

HttpCookie cookie = new HttpCookie("CookieNameHere");
cookie.Values["test1"] = "Value1";
cookie.Values["test2"] = "Value2";
cookie.Values["test3"] = "Value3";
//I have also tried cookie.Values.Add("test1", "Value1");

cookie.Expires = DateTime.Now.AddDays(365d);
HttpContext.Current.Response.AppendCookie(cookie); //here I have also tried HttpContext.Current.Response.Cookies.Add(cookie);

but when I read out the cookie using the following code:

HttpCookie cookie = new HttpCookie("CookieNameHere");
cookie = HttpContext.Current.Response.Cookies["CookieNameHere"];

I always get that the cookie.Values is empty

Is there something I am doing wrong here?

Upvotes: 1

Views: 621

Answers (2)

Ross McNab
Ross McNab

Reputation: 11567

Normally you would write the cookie in a Response, and then read it from subsequent Requests.

I see you're trying to read it from the Response - is this within the context of the same HTTP request, or just a typo?

Try

HttpCookie cookie = HttpContext.Current.Request.Cookies["CookieNameHere"];

Upvotes: 2

Jenda Matejicek
Jenda Matejicek

Reputation: 151

You have to ask for those Cookies in a Request.

HttpCookie cookie = Request.Cookies["CookieName"];

Upvotes: 1

Related Questions