HttpWebResponse.Cookies .net 框架和 .net 核心中的不同行为

HttpWebResponse.Cookies different behavior in .net framework and .net core

我正在从 .net framework 迁移到 .net core,发现 HttpWebRequest/HttpWebResponse 有一些奇怪的情况: 任务:需要将 HttpWebRequest 发送到带有值为“fail”的 cookie A 的某个地址,并从响应中获取 cookie A(但期望 cookie A 在响应 header 中具有值“Ok”)。 如果您尝试通过名称(例如 response.Cookies[“A”])从响应中获取 cookie,对于 .net framework 会得到“Ok”,而对于 .net core 会得到“fail”。

示例如下(1p_JAR 包含在请求和响应中):

CookieContainer cookieContainer = new CookieContainer();
Uri uri = new Uri("https://google.com");
cookieContainer.SetCookies(uri, "k1=1111,k2=2222,k3=3333,1P_JAR=zzz");

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.CookieContainer = cookieContainer;
request.Method = "GET";

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Console.WriteLine("Cookies from response: ");
foreach (Cookie cookie in response.Cookies)
{
    Console.WriteLine("    " + cookie.Name + ": " + cookie.Value);
}

Console.WriteLine("Get cookie by name: " + response.Cookies["1P_JAR"]);

.net 框架的结果:

Cookies from response:
    1P_JAR: 2018-10-26-13
    NID: bla-bla-bla
Get cookie by name: 1P_JAR=2018-10-26-13

.net 核心的结果:

Cookies from response:
    k1: 1111
    k2: 2222
    k3: 3333
    1P_JAR: zzz
    1P_JAR: 2018-10-26-13
    NID: bla-bla-bla
Get cookie by name: 1P_JAR=zzz

如何在 .net 核心中重复 HttpWebRequest/HttpWebResponse 的 .net Framework 实现行为?

在 github 中创建了问题:https://github.com/dotnet/corefx/issues/33122

适用于 .net 核心和 .net 框架的解决方案:

public static class HttpWebResponseGetCookiesExtension
{
    public static CookieCollection GetResponseCookies(this HttpWebResponse response)
    {
#if NETCOREAPP
        var cookieContainer = new CookieContainer();
        string cookieHeader = response.Headers[HttpResponseHeader.SetCookie] ?? string.Empty;
        cookieContainer.SetCookies(response.ResponseUri, cookieHeader);
        return cookieContainer.GetCookies(response.ResponseUri);
#else
        return response.Cookies;
#endif
    }
}