MVC, Cookies, jQuery... is my cookie being cached?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • peridian
    New Member
    • Dec 2006
    • 72

    #1

    MVC, Cookies, jQuery... is my cookie being cached?

    Hi,

    Been trying to get to the bottom of a bug, which I thought was the browsers fault, but it turns out is either:

    a) a bug in the browser.
    b) a bug in jquery cookie handler.
    c) a bug in MVC response handler.

    Simple way to replicate this...

    Controller

    Code:
    public class HomeController : Controller
    {
        public ViewResult Index(String id)
        {
            var cookie = Request.Cookies["test"] ?? new HttpCookie("test") { Expires = DateTime.Now.AddDays(1) };
    
            cookie.Value = (!String.IsNullOrEmpty(id)) ? id : "a new cookie";
    
            Response.Cookies.Add(cookie);
    
            return View();
        }
    }
    View

    Code:
    <div id="debug"></div>
    
    <script type="text/javascript" src="/Scripts/jquery.cookie.js"></script>
    <script type="text/javascript">
        var cookieString = $.cookie("test");
        $("#debug").html(cookieString);
        $.cookie("test", cookieString + " another bit");
    </script>
    (Note: Use the path /Home/Index/{id}, since using the root path (/) appears to work as it should.)

    Now, when you load up the page for the first time, you'll see the text "a new cookie" (or whatever you put as the id).

    If you hit refresh, the server will receive back the modified cookie (i.e. what jquery modified). BUT you should still see the same output result since the server code should reset the cookie.

    But instead, it just keeps adding " another bit" on to the end continuously.

    Am I missing something really obvious? Or is the cookie getting cached somewhere and ignoring the server update?

    Originally I thought the problem was if you put in an {id}, and then manually changed the address to /Home/Index without an {id}, somehow the cookie update by javascript was being dropped.

    I also thought that this was working fine in Firefox, and only IE had the problem, but I've since seen the same behaviour in Firefox.

    Regards,
    Rob.
  • Oralloy
    Recognized Expert Contributor
    • Jun 2010
    • 988

    #2
    @peridian,

    The code is working as you wrote it.

    Line 7 of your controller simply copies back the cookie to the view each time you refresh the page.

    Basically, the (returned) cookie is sent to the view "as-is" when it's set, and set to "a new cookie", only if it doesn't exist.

    So, since the view updates the cookie each pass, you see the sequence:
    ""
    "a new cookie"
    "a new cookieanother bit"
    "a new cookieanother bitanother bit"
    "a new cookieanother bitanother bitanother bit"
    ...

    Am I making sense to you?

    Comment

    • peridian
      New Member
      • Dec 2006
      • 72

      #3
      So you're saying that cookie.Value = "a new value" does not actually set the value of the cookie that is sent back??

      Regardless of whether the cookie already existed or not (i.e. line 5 creates a new one or uses the existing one), line 7 should have reset the value.

      Comment

      • Oralloy
        Recognized Expert Contributor
        • Jun 2010
        • 988

        #4
        I could be that I misunderstand line 5.

        Aren't you saying to create a new cookie, only if Request.Cookies["test"] does not exist?

        This page might help. It's a reference for the ?? operator.

        Of course, now that I look at your code some more, what's the value of id supposed to be?

        Comment

        • peridian
          New Member
          • Dec 2006
          • 72

          #5
          Note: All of this code is test code, derived from my actual code. My actual code is more complicated but this simplifies demonstration of the problem.

          Value of Id could be anything, its only there for testing purposes (you can actually remove the parameter and the reference to it on line 7, and the same problem still occurs).

          In MVC routing, the id parameter is optional, it was just so I could test what happens if I change the value it uses to set the cookie value, rather than constantly using "a new value".

          This code should run line 5, which says grab the existing cookie if there is one, and if not, then create a new one (that is intentional, the use of the ?? was a concise way to ensure that a cookie would exist if it did not already).

          Regardless of whether it used the existing one or a newly created one, line 7 should then run and set the Value property of the cookie object, regardless of whether it had already been set, modified, or not.

          The next line should add the cookie back to the response and send it back to the browser.

          It's as though the '.Value =' line is only applicable after it first instantiates the cookie.

          When I debug the code, I can see the modified cookie coming in, and that in the runtime when it sets Value, the resulting object is setup correctly. I can also see that the Cookies collection correctly stores the object with the updated value.

          But when I debug the script in the browser, it clearly see the old cookie value, not the new one.

          Weird.

          Comment

          • peridian
            New Member
            • Dec 2006
            • 72

            #6
            Finally figured this out.

            You were right, it is technically doing what I have asked it to, what is misleading is the encapsulation of the data that Microsoft has chosen to employ.

            If you look at Response.Cookie s when it first loads the code, it is empty.

            If Request.Cookies has the cookie already set up in there, when it does Response.Cookie s.Add, the Response.Cookie s collection shows the added cookie on its own (as expected)

            HOWEVER so does the Request.Cookies .

            It appears that Response.Cookie s is some kind of sub-collection of Request.Cookies . They aren't the same collection but they are interlinked.

            So although Response.Cookie s implies that you are responding with only the one cookie

            IN FACT you are sending the contents of Request.Cookies back, which contains two cookies. The newly modified one AND the original.

            From that point on the code is just adding duplicates to the collection, and all code is only ever working with one of the cookies (selected presumably by the order they appear in), so it looks like the cookie is never being changed, when in fact it is but is being stored alongside the original.

            After some further testing, it appears that in order to get this right, you must set the expiry date of the incoming cookie you are updating so that it expires at the browser side, and then actively remove it from the Request.Cookies (call .Remove) before you add it to the Response.Cookie s collection.

            Otherwise it keeps duplicating.

            Rob.

            Comment

            • Oralloy
              Recognized Expert Contributor
              • Jun 2010
              • 988

              #7
              Rob,

              For some reason I didn't see a notification of your response last week. Sorry for dropping the conversation like that, I know how frustrating these bugs can be, and when you're finally talking with someone, and they disappear, well that's just annoying (having been there a few times myself).

              Anyway, I'm glad you solved your problem with the sequencing of cookies, and the odd mixing of request and response cookies. I'd have thought those two lists would have been maintained completely independently, even though many of the cookies (session, etc) should be similar or identical between the two.

              Thanks for posting your success, I've added it to my personal knowledge base.

              Cheers!

              Comment

              Working...