c# - 在 .net 4.5 中努力尝试使 cookie 无法响应 HttpClient

标签 c# async-await dotnet-httpclient

我得到了以下成功运行的代码。我不知道如何从响应中获取 cookie。我的目标是我希望能够在请求中设置 cookie 并从响应中获取 cookie。想法?

private async Task<string> Login(string username, string password)
{
    try
    {
        string url = "http://app.agelessemail.com/account/login/";
        Uri address = new Uri(url);
        var postData = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("username", username),
            new KeyValuePair<string, string>("password ", password)
        };

        HttpContent content = new FormUrlEncodedContent(postData);
        var cookieJar = new CookieContainer();
        var handler = new HttpClientHandler
        {
            CookieContainer = cookieJar,
            UseCookies = true,
            UseDefaultCredentials = false
        };

        var client = new HttpClient(handler)
        {
            BaseAddress = address
        };


        HttpResponseMessage response = await client.PostAsync(url,content);
        response.EnsureSuccessStatusCode();
        string body = await response.Content.ReadAsStringAsync();
        return body;
    }
    catch (Exception e)
    {
        return e.ToString();
    }
}

完整答案如下:

HttpResponseMessage response = await client.PostAsync(url,content);
response.EnsureSuccessStatusCode();

Uri uri = new Uri(UrlBase);
var responseCookies = cookieJar.GetCookies(uri);
foreach (Cookie cookie in responseCookies)
{
    string cookieName = cookie.Name;
    string cookieValue = cookie.Value;
}

最佳答案

要向请求添加 cookie,请在请求之前使用 CookieContainer.Add(uri, cookie) 填充 cookie 容器。发出请求后,cookie 容器将自动填充响应中的所有 cookie。然后您可以调用 GetCookies() 来检索它们。

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();

关于c# - 在 .net 4.5 中努力尝试使 cookie 无法响应 HttpClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13318102/

相关文章:

c# - 如何使用 HttpClient 从特定 IP 地址发送请求? C#

dependency-injection - 使用 IHttpFactory 注入(inject)服务时,构造函数无法位于 Blazor 服务器中

c# - 使用 MVC 显示表单错误

c# - IO绑定(bind)异步任务不异步执行

c# - Parallel.ForEach 与 Task.Run 和 Task.WhenAll

c# - 从 C# 中的yield 返回 IEnumerable<T>

c# - 如何测试类的实例是否为特定泛型类型?

javascript - 如何将 JavaScript 变量值赋给 JavaScript 数组?

c# - 如何将属性 setter 链接到委托(delegate)?

c# - 为什么 HttpClient 总是给我相同的响应?