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

后端 未结 2 1496
太阳男子
太阳男子 2021-01-02 10:16

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

HttpCookie aCookie = new HttpCookie("userIn         


        
2条回答
  •  萌比男神i
    2021-01-02 11:13

    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 FromLegacyCookieString(this string legacyCookie)
        {
            return legacyCookie.Split('&').Select(s => s.Split('=')).ToDictionary(kvp => kvp[0], kvp => kvp[1]);
        }
    
        public static string ToLegacyCookieString(this IDictionary 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()
    {
        { "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.

提交回复
热议问题