I'm going nuts over this. I can write to a cookie, and then read it again. But at some point, i want to update the value it holds. Whenever i get the cookie again, i get the initial value, not the updated one. Below is the code i use for write/update and read of the cookie.
private static HttpCookie WriteCookie(Guid siteId, string siteName)
{
var cookie = HttpContext.Current.Request.Cookies.Get("UserSettings");
if(cookie != null) {
cookie.Value = EncryptObject(new UserSettingsModel { SiteID = siteId, SiteName = siteName });
HttpContext.Current.Response.Cookies.Set(cookie);
}else {
cookie = new HttpCookie("UserSettings") { Path = "/", Expires = DateTime.Now.AddDays(1), Value = EncryptObject(new UserSettingsModel { SiteID = siteId, SiteName = siteName }) };
HttpContext.Current.Response.Cookies.Add(cookie);
}
return cookie;
}
public static UserSettingsModel GetUserSettings(string username = null)
{
var cookie = HttpContext.Current.Request.Cookies.Get("UserSettings");
if (cookie == null || string.IsNullOrEmpty(cookie.Value))
{
cookie = ResetUserSettings();
}
var userSettings = DecryptObject<UserSettingsModel>(cookie.Value);
if (userSettings != null)
{
var siteId = userSettings.SiteID;
var siteName = userSettings.SiteName;
return new UserSettingsModel { SiteID = siteId, SiteName = siteName };
}
throw new SecurityException("You have no site attached to your user. Contact an administrtor.");
}
GetUserSettings
always returns the value that the cookie was initially created with. What's wrong?
EDIT:
I tried calling WriteCookie directly from a method in a Controller. The cookie was now set. I usually called WriteCookie via an Ajax request. Now, do i really have to write the cookie using JavaScript, or can i somehow just do it using WriteCookie?
Thanks!
Try like this:
But I suspect that your actual problem is that you are calling the
WriteCookie
method and theGetUserSettings
method in the same HTTP request which doesn't work as you might think it would or as you might expect it to.The
WriteCookie
writes the cookie to Response so that it is available on subsequent requests but theGetUserSettings
reads the cookie from the Request so you are getting the value of the cookie that was initially set when this request was initiated which of course is the old value. So after calling theWriteCookie
to update the value of the user settings cookie, perform a redirect and only on the subsequent request use theGetUserSettings
method.Also in ASP.NET MVC you typically don't want to use the static
HttpContext.Current
object but use the abstractions that this framework provides to you. I know you wrote those 2 methods as static but you should have written them as an extension method to theHttpContextBase
object for example. This way you could have called them anywhere where you had an instance of this abstract base class which ASP.NET MVC provides you in many common places during the lifetime of an HTTP request.