Struggling trying to get cookie out of response with HttpClient in .net 4.5

后端 未结 3 583
自闭症患者
自闭症患者 2020-11-28 20:03

I\'ve got the following code that works successfully. I can\'t figure out how to get the cookie out of the response. My goal is that I want to be able to set cookies in th

相关标签:
3条回答
  • 2020-11-28 20:28

    You can easily get a cookie value with the given URL.

    private async Task<string> GetCookieValue(string url, string cookieName)
    {
        var cookieContainer = new CookieContainer();
        var uri = new Uri(url);
        using (var httpClientHandler = new HttpClientHandler
        {
            CookieContainer = cookieContainer
        })
        {
            using (var httpClient = new HttpClient(httpClientHandler))
            {
                await httpClient.GetAsync(uri);
                var cookie = cookieContainer.GetCookies(uri).Cast<Cookie>().FirstOrDefault(x => x.Name == cookieName);
                return cookie?.Value;
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-28 20:29

    There's alternative if you don't have access to the HttpClient and can't inject the CookieContainer. This works in .NET Core 2.2:

    private string GetCookie(HttpResponseMessage message)
    {
        message.Headers.TryGetValues("Set-Cookie", out var setCookie);
        var setCookieString = setCookie.Single();
        var cookieTokens = setCookieString.Split(';');
        var firstCookie = cookieTokens.FirstOrDefault();
        var keyValueTokens = firstCookie.Split('=');
        var valueString = keyValueTokens[1];
        var cookieValue = HttpUtility.UrlDecode(valueString);
        return cookieValue;
    }
    
    0 讨论(0)
  • 2020-11-28 20:31

    To add cookies to a request, populate the cookie container before the request with CookieContainer.Add(uri, cookie). After the request is made the cookie container will automatically be populated with all the cookies from the response. You can then call GetCookies() to retreive them.

    CookieContainer cookies = new CookieContainer();
    HttpClientHandler handler = new HttpClientHandler();
    handler.CookieContainer = cookies;
    
    HttpClient client = new HttpClient(handler);
    HttpResponseMessage response = client.GetAsync("http://google.com").Result;
    
    Uri uri = new Uri("http://google.com");
    IEnumerable<Cookie> responseCookies = cookies.GetCookies(uri).Cast<Cookie>();
    foreach (Cookie cookie in responseCookies)
        Console.WriteLine(cookie.Name + ": " + cookie.Value);
    
    Console.ReadLine();
    
    0 讨论(0)
提交回复
热议问题