如何在ASP.NET Core中处理多值Cookie? [英] How to handle multi value cookies in ASP.NET Core?

查看:373
本文介绍了如何在ASP.NET Core中处理多值Cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在整个.NET框架中,我们支持多值cookie.例如Cookie可以具有多个值:

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

另请参见 MSDN上的ASP.NET Cookies概述.

使用ASP.NET Core,多值cookie似乎消失了.没有HttpCookie.Values 返回 ,就像从stringstring

dictionary

我现在应该如何在ASP.NET Core中创建和读取多值cookie?如何读取在Full ASP.NET中创建的多值cookie,并在ASP.NET Core中读取它们?

解决方案

我相信ASP.NET Core删除了对旧的旧式多值Cookie的支持,因为该功能从未标准化.

cookie的RFC定义明确指出,使用Set-Cookie标头可以分配一个单个名称/值对,并可选地关联了元数据.

.NET HttpCookieValues属性的正式实现非常脆弱,仅将键/值对与字符串进行序列化/反序列化,对字符串使用分隔符&,对值使用=分隔./p>

在ASP.NET核心中模拟这种行为应该非常容易,您可以使用扩展方法来处理那些旧格式的cookie:

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)));
    }
}

像这样使用它们:

// 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());

演示: https://dotnetfiddle.net/7KrJ5S

如果您需要更复杂的序列化/反序列化逻辑(可处理格式错误并转义cookie值中的字符),则应查找并从

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 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?

解决方案

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.

这篇关于如何在ASP.NET Core中处理多值Cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆