Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 861
Julian Avatar asked Apr 29 '17 22:04

Julian


People also ask

How do I store multiple values in a cookie?

To store multiple key-value pairs in a cookie, you have to create a custom object, convert it to a JSON string with the help of the “stringify()” method, and store the resultant “document. cookie” object.

What are multivalued cookies?

Multivalued Cookies: A single Cookie can store multiple values and those values are like a subkey for a key.

What is AspNetCore session cookie?

Session uses a cookie to track and identify requests from a single browser. By default, this cookie is named . AspNetCore. Session , and it uses a path of / . Because the cookie default doesn't specify a domain, it isn't made available to the client-side script on the page (because HttpOnly defaults to true ).

How many types of cookies are there in asp net?

There Are Two types of Cookies. Session Cookies: Are stored in memory during the client browser session. When the browser is closed the session cookies are lost. Persistent Cookies: Are used to store information that identifies a returning user to a web site.


1 Answers

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.

like image 117
Federico Dipuma Avatar answered Sep 18 '22 18:09

Federico Dipuma