11

In the full .NET framework we have support for multi value cookies. e.g. a cookie could have multiple values:

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

See also the docs about HttpCookie.Values on MSDN and ASP.NET Cookies Overview on MSDN.

With ASP.NET Core, the multi value cookie seems to be gone. There is no HttpCookie.Values and HttpRequest.Cookies returns a IRequestCookieCollection which is like a dictionary from string to string

How should I now create and read multi value cookies in ASP.NET Core? How could I read the multi value cookies created in Full ASP.NET and read them in ASP.NET Core?

1
  • 1
    Have you tried reading a "legacy" cookie? That might give some insight. A legacy NameValueCollection could be serialized to/from string pretty straightforwardly. It would be interesting to find out why the legacy multi value cookie is not natively supported by core. Commented May 6, 2017 at 19:56

2 Answers 2

35
+50

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

The RFC definition for cookies explicitly states that using the Set-Cookie header you can assign a single name/value pair, with optionally metadata associated.

The official implementation of Values property for .NET HttpCookie is very brittle, and just serializes/deserializes key-value pairs to/from a string with separators & for pairs and = for values.

Mocking this behavior in ASP.NET core should be fairly easy, you could use extension methods to handle those 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 need a more complex serialization/deserialization logic (which handles formatting errors and escapes characters in cookie values) you should look and grab some code from the Mono HttpCookie implementation, which, I believe, is a little more robust.

Sign up to request clarification or add additional context in comments.

2 Comments

How do you integrate the Mono HttpCookie implementation in a living ASP.NET Core system?
Note that ASP.NET Core will encode your special characters such as = in the cookie value. So you if you need interoperability with legacy applications, you need to look for solution here: stackoverflow.com/a/48324815
4

CookieManager wrapper allows you to play with objects. you can easily read/write object in asp.net core. it offers you to encrypt the cookie value to secure your data

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

Create your poco/object what 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 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 the myCookie object

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.