【问题标题】:How to store cookies using HttpClient in C#?如何在 C# 中使用 HttpClient 存储 cookie?
【发布时间】:2020-05-27 15:25:27
【问题描述】:

我正在尝试使用 HttpClient 将一些数据从我的应用程序传输到特定的 Web 服务。为此,我首先必须登录到 Web 服务并接收 cookie(这是 Web 服务使用的身份验证方法)。我是这样做的:

Uri uri = "login_uri";
CookieContainer CookieContainer_login = new CookieContainer();
HttpClientHandler ch = new HttpClientHandler
{
   AllowAutoRedirect = true,
   CookieContainer = CookieContainer_login,
   UseCookies = true
};
HttpClient client = new HttpClient(ch);
List<KeyValuePair<string, string>> pairs = new List<KeyValuePair<string, string>>
{
   new KeyValuePair<string, string>("user", "test"),
   new KeyValuePair<string, string>("password", "test"),
   new KeyValuePair<string, string>("loginSource", "0")
};
FormUrlEncodedContent content = new FormUrlEncodedContent(pairs);
System.Threading.Tasks.Task<HttpResponseMessage> response = client.PostAsync(uri, content);

它有效,我通过 Fiddler 收到有关成功登录的消息。现在,为了使用 Web 服务(另一个 Uri),例如发送 POST 请求,我必须将我的 cookie(在登录过程中收到)传递给该请求。当我将 cookie 存储在名为 CookieContainer_login 的 CookieContainer 中时,我想,我可以简单地使用相同的客户端,只更改 PostAsync 方法中的 Uri 或使用相同的 HttpClientHandler 和 CookieContainer 创建一个新客户端。不幸的是,它没有用。实际上,我发现我的 CookieContainer 是空的,即使在登录过程之后也是如此。

我尝试使用 HttpWebRequest 重新创建它:

string url_login = "login_uri";
string logparam = "user=test&password=test&loginSource=0";
HttpWebRequest loginRequest = (HttpWebRequest)WebRequest.Create(url_login);
loginRequest.ContentType = "application/x-www-form-urlencoded";
loginRequest.Accept = "text/xml";
loginRequest.Method = "POST";
loginRequest.CookieContainer = CookieContainer_login;

byte[] byteArray = Encoding.UTF8.GetBytes(logparam);

loginRequest.ContentLength = byteArray.Length;

Stream dataStream_login = loginRequest.GetRequestStream();
dataStream_login.Write(byteArray, 0, byteArray.Length);

它工作,我也收到成功登录消息,但当我检查 CookieContainer 计数时,它显示登录后正在存储的 3 个 cookie。现在我的问题是,为什么 HttpClient 在 CookieContainer 中没有 cookie,而 HttpWebRequest 却有?如何通过 HttpClient 获取 cookie?

【问题讨论】:

    标签: c# web-services cookies httpwebrequest dotnet-httpclient


    【解决方案1】:

    好的,我设法解决了我的问题,希望我的回答对有类似问题的人有用。就我而言,错误在于方法 PostAsync 调用。这是一种异步方法,因此它需要我缺少的 await 运算符。正确的方法调用应该如下所示:

    HttpResponseMessage response = new HttpResponseMessage(); response = await client.PostAsync(uri, content);

    现在所有的 cookie 都存储在我的 CookieContainer 中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-05
      • 1970-01-01
      • 2012-05-31
      • 2011-02-02
      • 2012-02-20
      • 1970-01-01
      • 2017-06-26
      • 2016-09-01
      相关资源
      最近更新 更多