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

后端 未结 3 601
自闭症患者
自闭症患者 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 20:28

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

    private async Task 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().FirstOrDefault(x => x.Name == cookieName);
                return cookie?.Value;
            }
        }
    }
    

提交回复
热议问题