來自CookieContainer
的Cookie不會添加到獲取或發佈請求中。其他頭文件沒有問題。什麼是添加cookie的正確方法?我以前做過這個沒有問題,但我找不到這裏的錯誤。C#HttpClient不會添加來自CookieContainer的Cookie以請求
var cookieContainer = new CookieContainer();
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
handler.UseCookies = true;
handler.CookieContainer = cookieContainer;
var baseAddress = new Uri("https://www.example.se");
cookieContainer.Add(baseAddress, new Cookie("Testing", "Test"));
//This did not work either
//cookieContainer.Add(baseAddress, new Cookie("Testing", "Test", "/"));
using (var client = new HttpClient(new LoggingHandler(handler)))
{
client.BaseAddress = baseAddress;
client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36");
client.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
client.DefaultRequestHeaders.Add("Accept-Language", "sv-SE,sv;q=0.8,en-US;q=0.6,en;q=0.4");
var getResponse = client.GetAsync("/test").Result;
string responseString = getResponse.Content.ReadAsStringAsync().Result;
}
LoggingHandler:使用CookieContainer
當 https://stackoverflow.com/a/18925296/3850405
您可以嘗試Cookie ctor重載,該重載也接受路徑作爲第三個參數,然後將「/ test」添加爲路徑,然後重試以查看是否確實呈現了預期結果。如果有效,我們可以回頭讓它工作在你最初希望的狀態, – rene