我正在通过发帖请求发送表单数据,我知道该请求会返回cookie,但是我的cookie变量将返回为空
我已经尝试过使用GetCookies,但是我想知道是否可以在收到200条响应后从我的PostAsync Response中过滤掉这些Cookie
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
HttpClient client = new HttpClient(handler);
HttpContent content = new StringContent(JsonConvert.SerializeObject(formVals), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(targetURI.AbsoluteUri , content);
IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetURI).Cast<Cookie>()
foreach (Cookie cookie in responseCookies)
result.Add(cookie);
我希望有2个Cookie能够返回并存储在我的responseCookies容器中
答案 0 :(得分:0)
您的问题有一些不清楚的方面:cookies
变量来自哪里,handler
变量来自哪里?这些细节对于回答问题很重要。
我认为您的代码可能有2个错误的部分。首先,您应该将CookieContainer
附加到您的处理程序:
var cookies = new CookieContainer();
var handler = new HttpClientHandler() { CookieContainer = cookies };
var client = new HttpClient(handler);
var content = new StringContent(JsonConvert.SerializeObject(formVals), Encoding.UTF8, "application/json");
var response = await client.PostAsync(targetURI.AbsoluteUri, content);
IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetURI).Cast<Cookie>()
foreach (Cookie cookie in responseCookies)
result.Add(cookie);
第二步(假设您的cookies
和handler
变量是通过这种方式初始化的),您可能需要获取cookie以获取正确的基地址(Uri.Host
):
IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetURI.Host).Cast<Cookie>()
如果您不确定,请与this approach(基于反射的深入检查)一起检查是否设置了cookie,以及它们是针对哪个域设置的。
答案 1 :(得分:0)
请大家知道,问题是我没有对表单数据进行编码。 将内容更改为下面的行。
var content = new FormUrlEncodedContent(formVals);