views:

55

answers:

3
+2  Q: 

Cookies in ASP.Net

I set a cookie like this in one page:

Request.Cookies["lang"].Value = "en-US";
Request.Cookies["lang"].Expires = DateTime.Now.AddDays(50); 

On another page I try and read the cookie:

string lang = Server.HtmlEncode(Request.Cookies["lang"].Value);

The cookie is not null but the value is an empty string. What am I doing wrong?

+1  A: 

Are cookies enabled on the client? The fact that you set a cookie doesn't mean that the client supports them and will send them back.

Remember, you're dealing with two disconnected systems; your server doesn't keep state and you know little about the client.

Esteban Araya
@Esteban Sometimes the simplest answer is the one you often forget. Didn't even think about having him check that.
spinon
Yes cookies is enabled in my browser. If I try and read the cookie after setting it on the same page the correct value is returned. But if I read it on a different page it returns an empty string.
Arizona1911
@Arizona1911: That's happening because you're setting the cookies in the `Request` rather than the `Response`.
LukeH
+1  A: 

If I remember correctly I think you should be using response instead of request as request is what is being sent to you. Response is when you want to set something back to the client browser.

EDIT: What you are doing is modifying the cookies in that particular request which would make sense why you are not seeing on subsequent pages. That is not saving them back to the client.

spinon
+8  A: 

You should be using Response.Cookies to set the cookie, and Request.Cookies to read any cookies sent back from the client.

The code in your question is setting the cookie in the Request object, not the Response.

LukeH
Also note that cookies set in Response will not appear in Request until the next page load.
David Lively
Thank you sir. This is the answer.
Arizona1911