Storing multiple values in cookies

后端 未结 3 497
盖世英雄少女心
盖世英雄少女心 2020-12-02 14:41

I have very large website which uses a lot of cookies. There are approx. 14 different cookies are there. I have different cookies for each item. When a user surfs the site t

相关标签:
3条回答
  • 2020-12-02 15:05

    Modifying and Deleting Cookies: You cannot directly modify a cookie. Instead, changing a cookie consists of creating a new cookie with new values and then sending the cookie to the browser to overwrite the old version on the client.

    0 讨论(0)
  • 2020-12-02 15:06

    Matthew beat me to it, but yes, see the ASP.NET Cookies Overview...

    To write and read a single cookie with multiple key/values, it would look something like this:

    HttpCookie cookie = new HttpCookie("mybigcookie");
    cookie.Values.Add("name", name);
    cookie.Values.Add("address", address);
    
    //get the values out
    string name = Request.Cookies["mybigcookie"]["name"];
    string address = Request.Cookies["mybigcookie"]["address"];
    
    0 讨论(0)
  • 2020-12-02 15:16

    There is a section in the ASP.NET Cookies Overview that discusses how to implement multiple name-value pairs (called subkeys) in a single cookie. I think this is what you mean.

    The example from that page, in C#:

    Response.Cookies["userInfo"]["userName"] = "patrick"; //userInfo is the cookie, userName is the subkey
    Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString(); //now lastVisit is the subkey
    Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(1);
    
    HttpCookie aCookie = new HttpCookie("userInfo");
    aCookie.Values["userName"] = "patrick";
    aCookie.Values["lastVisit"] = DateTime.Now.ToString();
    aCookie.Expires = DateTime.Now.AddDays(1);
    Response.Cookies.Add(aCookie);
    

    EDIT: From the Cookies Overview (emphasis added):

    Modifying and Deleting Cookies: You cannot directly modify a cookie. Instead, changing a cookie consists of creating a new cookie with new values and then sending the cookie to the browser to overwrite the old version on the client.

    0 讨论(0)
提交回复
热议问题