How to handle multi-value cookies in ASP.NET Core?

In the full .NET framework, we support multi-value cookies. for example, a cookie can have several values:

HttpCookie aCookie = new HttpCookie("userInfo");
aCookie.Values["userName"] = "patrick";
aCookie.Values["lastVisit"] = DateTime.Now.ToString();

      

See also the docs HttpCookie.Values

on MSDN
and ASP.NET Cookies Overview on MSDN .

In ASP.NET Core, a lot of multi-value cookies seem to be gone. No HttpCookie.Values

and HttpRequest.Cookies

returns IRequestCookieCollection

that are similar to dictionary

from string

tostring

How do I now create and read multiple value cookies in ASP.NET Core? How can I read multi-value cookies created in Full ASP.NET and read them in ASP.NET Core?

+3


source to share


2 answers


I believe ASP.NET Core removed support for the old old multi-value cookies because this feature was never standardized.

the RFC definition for cookies explicitly states that with a header, Set-Cookie

you can assign a single name / value pair, with optional metadata associated.

The official property implementation Values

for .NET is HttpCookie

very fragile and just serializes / deserializes key-value pairs to / from a string delimited &

for pairs and =

for values.

Rejecting this behavior in ASP.NET core should be pretty simple, you could use extension methods to handle these legacy formatted cookies:

public static class LegacyCookieExtensions
{
    public static IDictionary<string, string> FromLegacyCookieString(this string legacyCookie)
    {
        return legacyCookie.Split('&').Select(s => s.Split('=')).ToDictionary(kvp => kvp[0], kvp => kvp[1]);
    }

    public static string ToLegacyCookieString(this IDictionary<string, string> dict)
    {
        return string.Join("&", dict.Select(kvp => string.Join("=", kvp.Key, kvp.Value)));
    }
}

      



Using them like this:

// read the cookie
var legacyCookie = Request.Cookies["userInfo"].FromLegacyCookieString();
var username = legacyCookie["userName"];

// write the cookie
var kvpCookie = new Dictionary<string, string>()
{
    { "userName", "patrick" },
    { "lastVisit", DateTime.Now.ToString() }
};
Response.Cookies.Append("userInfo", kvpCookie.ToLegacyCookieString());

      

Demo: https://dotnetfiddle.net/7KrJ5S

If you want more complex serialization / deserialization logic (which handles formatting errors and escapes characters in cookie values), you should look at and grab some code from Mono HttpCookie , which I find a little more robust.

+7


source


The CookieManager wrapper lets you play with objects. you can read / write the object easily in asp.net core. it prompts you to encrypt the cookie value to protect your data.

check: https://github.com/nemi-chand/CookieManager

Create your poco / object that you want to store in cookie.

public class MyCookie
{
  public string Id { get; set; }

  public DateTime Date { get; set; }

  public string Indentifier { get; set; }
}

      

fill in the object values



MyCookie cooObj= new MyCookie()
{
  Id = Guid.NewGuid().ToString(),
  Indentifier = "valueasgrsdgdf66514sdfgsd51d65s31g5dsg1rs5dg",
  Date = DateTime.Now
};

      

set the myCookie object

_cookieManager.Set("Key", cooObj, 60);

      

get myCookie object

MyCookie objFromCookie = _cookieManager.Get<MyCookie>("Key");

      

+3


source







All Articles