[英]How to retrieve Cookies from HttpResponseMessage
我在 post 请求中发送表单数据,我知道它返回 cookie,但我的 cookie 变量被返回为空
如您所见,我尝试使用 GetCookies,但我想知道是否可以在收到 200 响应时从 PostAsync 响应中过滤掉 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 容器中
您的问题中有一些不清楚的方面:您的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
变量以这种方式初始化),您可能需要为正确的基址( Uri.Host
)获取 cookie:
IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetURI.Host).Cast<Cookie>()
如果您完全不确定,请检查这种方法(基于反射的深度检查)是否设置了 cookie,以及它们是为哪个域设置的。
只是让你们知道,问题是我没有对我的表单数据进行编码。 将内容更改为下面的行。
var content = new FormUrlEncodedContent(formVals);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.