4

I am updating the cookie as follows

if (Request.Cookies["SSOPortalUser"] == null)
                {
                    HttpCookie myCookieSSOPortalUser = new HttpCookie("SSOPortalUser");
                    // Set the cookie value.
                    myCookieSSOPortalUser.Value = currentUser.UserLogin.ToString();

                    // Add the cookie.
                    Response.Cookies.Add(myCookieSSOPortalUser);
                }
                else
                {
                    Request.Cookies["SSOPortalUser"].Value = currentUser.UserLogin.ToString();
                }

But after I redirect to another page the is not updating in the browser

Response.Redirect(AppSettings.Instance.AppRoot + "OperationSelection.aspx");

and in the operationSelection Page I am trying to access the cookie it shows the previous value .

lbluser.Text = Request.Cookies["SSOPortalUser"].Value
Kapil
  • 1,823
  • 6
  • 25
  • 47
  • what is initial value of `Request.Cookies["SSOPortalUser"].Value` I mean when check evaluated to not null you assigning some value, right ? but what is value before assignment – rahulaga-msft Feb 09 '18 at 07:36
  • 4
    If cookie is present in request, you are changing value of request cookie, which has no effect because you need to set response cookie to update it. – Evk Feb 09 '18 at 07:43
  • Also, setting cookies during a redirect is a tricky subject: https://stackoverflow.com/questions/5366635/is-it-possible-to-set-a-cookie-during-a-redirect-in-asp-net – Kevin Gosse Feb 09 '18 at 07:57
  • 2
    @RacilHilan in "else" branch (which is entered if there is cookie attached to request) OP updates request cookie value. This does nothing useful, because to update cookie value on client one needs to attach new cookie (with new value) to response. Since OP says " it shows the previous value" I suspect that is the problem (because that means there was already cookie present and so "else" branch is used). – Evk Feb 09 '18 at 09:11
  • @Evk You only needed to say that your comment referred to the `else` branch :). For some reason, I overlooked it. It's strange that the OP did it differently from the `if` branch. Of course your comment is correct, +1. Thanks for the kind explanation. – Racil Hilan Feb 09 '18 at 09:28
  • @Evk you are right I have modified the else part to Response.Cookies instead of Request.Cookies and its working. – Kapil Feb 09 '18 at 09:33

1 Answers1

1

The problem, as figured out in comments, is caused by wrong assumption that updating request cookie value (in else branch) will somehow update cookie value on client. That's not so, because to update cookie on client you need to attach another cookie with the same name (and different value) to the response. Updating request cookie does nothing useful (just updates value of in-memory structure representing request cookie).

Evk
  • 98,527
  • 8
  • 141
  • 191