无论是.NET Framework 4.7.2还是.NET Core 6.0,C#的Cookie不支持key名为空字符或null,会抛出异常:System.Net.CookieException:“Cookie 的“Name”=“”部分无效。”
但比如百度的这个cookie,key名就是空字符串
所以C#对于这样的cookie无法构建
————————————————————————————————————————————————————————
CookieContainer类绑定到HttpClient上,但发请求时,只会对domain进行筛选,而不对path进行筛选,就导致请求一个URL时发的cookie不管path即子目录是否对的上也会被发
自己写的在.NET Framework 4.7.2、4.8下的测试代码:
static void Main(string[] args)
{
Cookie c1 = new Cookie();
c1.Name = "n";
c1.Value = "111";
c1.Path = "/share";
c1.Domain = "xxxxxxxmytest.org";
Cookie c2 = new Cookie();
c2.Name = "n";
c2.Value = "222";
c2.Path = "/s";
c2.Domain = "xxxxxxxmytest.org";
Cookie c3 = new Cookie();
c3.Name = "n";
c3.Value = "333";
c3.Path = "/";
c3.Domain = "xxxxxxxmytest.org";
Cookie c4 = new Cookie();
c4.Name = "n";
c4.Value = "444";
c4.Path = "/myfind";
c4.Domain = "xxxxxxxmytest.org";
Cookie c5 = new Cookie();
c5.Name = "n";
c5.Value = "555";
c5.Path = "/share";
c5.Domain = "test.xxxxxxxmytest.org";
Cookie c6 = new Cookie();
c6.Name = "n";
c6.Value = "666";
c6.Path = "/share";
c6.Domain = "xxxxxxxmytest2222.org";
CookieContainer container = new CookieContainer();
container.Add(c1);
container.Add(c2);
container.Add(c3);
container.Add(c4);
HttpClientHandler handler = new HttpClientHandler();
handler.AllowAutoRedirect = false;
handler.CheckCertificateRevocationList = false;
handler.CookieContainer = container;
handler.UseCookies = true;
HttpClient httpClient = new HttpClient(handler);
httpClient.Timeout = TimeSpan.FromSeconds(1);
httpClient.DefaultRequestHeaders.Clear();
httpClient.DefaultRequestHeaders.Connection.Add("keep-alive");
httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36");
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri("http://xxxxxxxmytest.org/share/add?time=xxx");
try
{
var task = httpClient.SendAsync(httpRequest);
task.Wait();
HttpResponseMessage response = task.Result;
if (response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
else
Console.WriteLine($"doGet请求{httpRequest.RequestUri}错误,返回状态码为{(int)response.StatusCode},描述为{response.StatusCode}");
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.Read();
}
.NET Framework 4.7.2、4.8中运行上面代码,并用Fiddler抓包,可以发现前3个cookie都发出去了
相比第3个,最无法接受的是第2个,明明path是/s,请求的URL是/share,这直接模糊匹配上都算了!
在.NET Core 6.0中运行结果只有1和3
但3这个cookie也不该被发出去的,任何一家浏览器处理cookie,都没有发path=/的,因为有更匹配的path=/share的