Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem saving/getting cookies in MVC 2

Try to save them like this:

HttpCookie latcook = new HttpCookie("latitude", lat.Value.ToString());
                HttpCookie lngcook = new HttpCookie("longitude", lng.Value.ToString());
                Request.Cookies.Add(latcook);
                Request.Cookies.Add(lngcook);

Everything has a value, and the code steps through without error.

Then immediately after those are set, I refresh my page and step through this:

HttpCookie latcook = Request.Cookies.Get("latitude");
                HttpCookie lngcook = Request.Cookies.Get("longitude");

The latcook and lngcook variables have names, but no values. What am I doing wrong?

like image 218
slandau Avatar asked Feb 04 '26 14:02

slandau


1 Answers

You are adding your cookies to the request object. They should be added to the response:

Response.Cookies.Add(latcook);
Response.Cookies.Add(lngcook);

Cookies added to the response are returned to the user's browser via a series of Set-Cookie HTTP headers. They are then subsequently sent back (upon the next request) via the Cookie HTTP header. (You should be able to watch this happen using Firebug, etc.) Ultimately, this header will be parsed and populate the Request.Cookies collection.

like image 146
Kirk Woll Avatar answered Feb 06 '26 03:02

Kirk Woll



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!