cookie problems in asp.net. Values reverting after response.redirect

淺唱寂寞╮ 提交于 2020-01-14 19:23:08

问题


I have spent sooooo many hours on this it is insane.

I have a page base class which contains a "setcookie" function and this is basically 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)
            context.Response.Cookies.Add(cookie)
        Else
            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. As this is in a test environment there is a previous value of "123" in the cookie I'm using. If I use the debug and watch window, I see the value change to "168" successfully.

I have a debug break point on a line which is:

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

When the break point is active, the values in the watch window 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 function above)

Now, the second I step off the breakpoint line above using "F10" the values of the variable change!

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

This is insane! The code goes nowhere, the debug point is immediately under the "response.redirect" line above and yet the values have immediately changed to what they were before! Nothing has gone near the "setcookie" routine so please please please would someone save my insanity and tell me what is going wrong!?


回答1:


You have to: - get the cookie from request - update cookie - send cookie in response

If you dont sent cookie in the response, browser wouldn't know anything about the change !!! Cookies aren't that clever to update themselves.

Hope it helps.

UPDATE

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

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

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

Response.Cookies.Add(cookieDetails);

Hope it helps.



来源:https://stackoverflow.com/questions/9708420/cookie-problems-in-asp-net-values-reverting-after-response-redirect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!