如何在C#中使用HttpClient存储cookie?

问题描述 投票:0回答:1

我正在尝试使用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时却存在cookie?如何也通过HttpClient获取cookie?

c# web-services cookies httpwebrequest dotnet-httpclient
1个回答
0
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.