I want someone who visits my internationalized site to be able to change the language. I thought best way would be to store the language chosen in a cookie - so when the pag
Try setting cookie.Path = "/";
Before you add the cookie.
first of all check for cookie is created or not.
for this use firefox and add webdeveloper plugin
After installing webdeveloper, a toolbar appear on firefox browser, select cookies tab on it
cookies -> View Cookies information it will display all cookies with their properties.
It sounds like the cookie is never being set. In which case you need to check for this:
HttpCookie aCookie = Request.Cookies["UserSettings"];
if(aCookie != null) {
object userSettings = aCookie.Value;
} else {
//Cookie not set.
}
To set a cookie:
HttpCookie cookie = new HttpCookie("UserSettings");
cookie["UserSettings"] = myUserSettingsObject;
cookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(cookie);
Here is a good article: http://www.java2s.com/Code/ASP/Session-Cookie/CreateandretrieveCookiedataC.htm
You create your cookie within Application_BeginRequest()
and add the results to the Response
. It will be created on the client side only after the response has been sent back.
But you are reading the cookie value from the Request
state, perhaps the original request before the response with the cookie has been sent back to the client? At this time within the life cycle however this cookie is not contained in the Request
and thus is null
.
Your client would have to send another request after the cookie has been created in order to make it available to the server and this makes perfect sense to me.
The reason that you can see the cookie in your web developer tools is, that the server will send the Response
back to the client. However it will not be present in the current Request
state, unless a new request with the cookie will be sent by the client.
Can you try this?
HttpCookie aCookie = Request.Cookies["UserSettings"];
string lang = Server.HtmlEncode(aCookie.Value);
http://msdn.microsoft.com/en-us/library/ms178194.aspx
EDIT Does this help you? asp.net mvc can't access cookie data in base controller
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie = Request.Cookies["UserSettings"];
string lang = myCookie.Value.ToString();