我知道您可以通过在请求处理程序中添加
CookieContainer
来获取 cookie。
但是,除非我将
UseCookies
设置为 false,否则以下发布请求将失败:
static CookieContainer cookies = new CookieContainer();
var clientHandler = new HttpClientHandler
{
//Original Apporach - this fails the POST request
// UseCookies = true,
// CookieContainer = cookies,
//I had to do this
UseCookies = false,
};
var client = new HttpClient(clientHandler);
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri("*redacted*"),
Headers =
{
{ "cookie", "SampleCookie" },
},
Content = new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "Provider", "Email" },
{ "Code", "12345" },
{ "RememberMe", "False" },
{ "RememberBrowser", "false" },
{ "__RequestVerificationToken", "SampleToken" },
}),
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
Console.WriteLine(body);
}
说实话,我对 HTTP 请求不太了解。我原来的方法是否失败,因为我手动设置 cookie?
请求失败的原因可能取决于很多因素 - 例如身份验证和所需的其他标头,如果不知道您尝试访问的内容的具体情况,就很难判断是什么原因导致的。 这是一个简单的示例,展示了如何向 Google 首页发出请求并将所有 cookie 放入容器中并在控制台应用程序中打印出来:
static void Main(string[] args)
{
var uri = new Uri("https://google.com");
var cookies = new CookieContainer();
var handler = new HttpClientHandler();
handler.CookieContainer = cookies;
using (var client = new HttpClient(handler))
{
var result = client.GetAsync(uri).Result;
}
foreach (Cookie cookie in cookies.GetCookies(uri))
{
var print = $"cookie name: {cookie.Name}\ncookie value: {cookie.Value}\n";
Console.WriteLine(print);
}
}
很多人仍然建议
UseCookies = false
发送/覆盖自定义cookie,这是错误的。
UseCookies = false
是禁用请求/响应cookie容器,我知道如果我这样做,我可以发送自定义标头Cookie
,但缺点是我无法读取cookie容器内的Response Cookie
甚至响应标头。
覆盖此设置的正确方法是在
CookieContainer
中设置 cookie
CookieContainer cookies = new CookieContainer();
// add your custom cookie here (key, value, path, domain)
Cookie customCookie = new Cookie("cookieKey", "cookieValue", "/", "example.com");
cookies.Add(customCookie);
var clientHandler = new HttpClientHandler
{
CookieContainer = cookies,
//UseCookies = false, // no need this
};
// no need to write
// Headers = { { "cookie", "cookieKey=cookieValue" } }