使用 OWIN ResponseCookieCollection 添加具有多个值的 cookie class

Add cookie with multiple values using OWIN ResponseCookieCollection class

我需要使用 OWIN API 来设置具有多个值的 cookie。

这可以使用 HttpCookie class 完成,如下所示:

var cookie = new HttpCookie("MyCookie");
cookie ["CustomField1"] = HttpUtility.UrlEncode(customValue1);
cookie ["CustomField2"] = HttpUtility.UrlEncode(customValue2);
this._httpContext.Response.Cookies.Set(cookie);

我如何使用 OWIN ResponseCookieCollection class 创建此 cookie?

https://msdn.microsoft.com/en-us/library/microsoft.owin.responsecookiecollection(v=vs.113).aspx

此 class 有一个 Append 方法用于添加新的 cookie 和值,但是不清楚如何添加具有多个值的 cookie。任何帮助将不胜感激。

事实证明 ResponseCookieCollection class 在 Append 方法中编码值。

这可以通过将多值 cookie 直接添加到 IHeaderDictionary 来解决。

代码:

public static class HeaderExtensions
{
    public static void SetMultiValuedCookie(
        this IHeaderDictionary headers,
        string key,
        params KeyValuePair<string, string>[] values)
    {
        if (string.IsNullOrWhiteSpace(key))
        {
            throw new ArgumentNullException(nameof(key));
        }

        if (values == null)
        {
            throw new ArgumentNullException(nameof(values));
        }

        if (0 >= values.Length)
        {
            throw new ArgumentOutOfRangeException(nameof(values));
        }

        var value = string.Join("&", values.Select(v => $"{Uri.EscapeDataString(v.Key)}={Uri.EscapeDataString(v.Value)}"));

        headers.AppendValues("Set-Cookie", Uri.EscapeDataString(key) + "=" + value + "; path=/");
    }
}

测试:

var headers = new HeaderDictionary(new Dictionary<string, string[]>());

var values = new[]
{
    new KeyValuePair<string, string>("CustomField1", "1"),
    new KeyValuePair<string, string>("CustomField2", "2"),
};

headers.SetMultiValuedCookie("MyCookie", values);
headers.SetMultiValuedCookie("MyCookie2", values);

结果: