C#HttpClient不会从CookieContainer添加Cookie来请求

时间:2017-04-07 11:31:48

标签: c# cookies dotnet-httpclient

来自CookieContainer的Cookie未添加到“获取”或“发布”请求中。其他标题工作没有问题。添加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: https://stackoverflow.com/a/18925296/3850405

enter image description here

1 个答案:

答案 0 :(得分:0)

由于某些原因,使用CookieContainer时,Cookie不在CookieContainer标头中。如果我检查了我的var cookieList = new List<Cookie>(); foreach (Cookie cookie in cookieContainer.GetCookies(baseAddress)) { cookieList.Add(cookie); } 对象,他们就在那里。

var DeckofCards = new Array('2D', '2H', '2S', '2C', '3D', '3H', '3S', '3C', '4D', '4H', '4S', '4C', '5D', '5H', '5S', '5C', '6D', '6H', '6S', '6C', '7D', '7H', '7S', '7C', '8D', '8H', '8S', '8C', '9D', '9H', '9S', '9C', '10D', '10H', '10S', '10C', '11D', '11H', '11S', '11C', '12D', '12H', '12S', '12C', '13D', '13H', '13S', '13C', '14D', '14H', '14S', '14C');

function shuffle(array) 
{
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) 
  {
    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;
    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

var output = shuffle(DeckofCards).slice(DeckofCards.length/2);
console.log(output);