Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to update cookie in ASP.NET

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!

like image 784
Andreas Avatar asked Jan 18 '12 10:01

Andreas


People also ask

How to add cookie to Http Request c#?

To send a request with a Cookie, you need to add the "Cookie: name=value" header to your request. To send multiple cookies in a single Cookie header, separate them with semicolons or add multiple "Cookie: name=value" request headers.

How do I update cookies in net core?

To update a cookie, you overwrite it with a new value. To delete a cookie, you set the expiration to yesterday.

What is HttpCookie in ASP net?

A cookie is a small bit of text that accompanies requests and pages as they go between the Web server and browser. The cookie contains information the Web application can read whenever the user visits the site.


1 Answers

Try like this:

var response = HttpContext.Current.Response;
response.Cookies.Remove("UserSettings");
response.Cookies.Add(cookie);

But I suspect that your actual problem is that you are calling the WriteCookie method and the GetUserSettings 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 the GetUserSettings 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 the WriteCookie to update the value of the user settings cookie, perform a redirect and only on the subsequent request use the GetUserSettings 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 the HttpContextBase 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.

like image 193
Darin Dimitrov Avatar answered Oct 13 '22 09:10

Darin Dimitrov