Problems with cookies in Values ​​returned after response.redirect

I've spent sooooo many hours, it's crazy.

I have a base page class that contains a setcookie function and it's basically like this:

        Dim context As HttpContext = System.Web.HttpContext.Current

        If context.Request.Cookies(cookieName) Is Nothing Then
            Dim cookie As HttpCookie
            cookie.Value = cookieValue
            cookie.Expires = DateTime.Now.AddDays(7)
            Dim cookie As HttpCookie = context.Request.Cookies(cookieName)
            cookie.Expires = DateTime.Now.AddDays(7)
            cookie.Value = cookieValue
        End If


This function is called by a simple aspx page. Since this is in a test environment, I am using the previous value "123" in the cookie. If I use the debug and view window, I see that the value changed to "168" successfully.

I have a debug breakpoint on a line that:

           Response.Redirect("overview.aspx", False)


When the breakpoint is active, the values ​​in the viewport are:

    currProjectID   168 Integer
    HttpContext.Current.Request.Cookies("currProjectID").Value  "168"   String


(currProjectID is a property in the basepage class that gets / sets the cookie with the above function)

Now, second, I remove the breakline above using "F10" the value of the variable change!

    HttpContext.Current.Request.Cookies("currProjectID").Value  "123"   String
    currProjectID   123 Integer


This is madness! The code is nowhere to be found, the debug point is directly below the "response.redirect" line above, and yet the values ​​immediately changed to what they were before! Nothing comes close to the "setcookie" procedure, so please, please, someone will save my madness and tell me what is going wrong !?


source to share

1 answer

You should: - get cookie from request - update cookie - send cookie in response

If you didn't send a cookie in response, the browser won't know anything about the change !!! Cookies are not smart enough to update themselves.

Hope it helps.


var cookieDetails = Request.Cookies["yourCookie"];
if (cookieDetails != null)
    cookieDetails.Values["someValue"] = valueToAssign;
    cookieDetails = new HttpCookie("yourCookie");
    cookieDetails.Values.Add("someValue", valueToAssign);


this example sets a cookie. as you can see the first bit checks if the cookie exists and the second creates a new cookie.

you are missing the last bit that sends the cookie back to the browser



Hope it helps.



All Articles