[英]How to retrieve Cookies from HttpResponseMessage
I am sending form data in a post request which I know returns cookies but my cookie variable is being returned as empty我在 post 请求中发送表单数据,我知道它返回 cookie,但我的 cookie 变量被返回为空
I've tried using GetCookies as you can see but I'm wondering if I can filter the cookies out of my PostAsync Response as I get a 200 response如您所见,我尝试使用 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);
I expect 2 cookies to come back and be stored in my responseCookies Container我希望 2 个 cookie 返回并存储在我的 responseCookies 容器中
There are some unclear aspects in your question: where does your cookies
variable come from, and where does your handler
variable come from?您的问题中有一些不清楚的方面:您的cookies
变量来自哪里,您的handler
变量来自哪里? These details are important to answer the question.这些细节对于回答这个问题很重要。
I can think of 2 possible wrong parts of your code.我可以想到您的代码中有 2 个可能的错误部分。 First, you should attach a CookieContainer
to your handler:首先,您应该将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);
Secondly (assuming your cookies
and handler
variables were initialized that way), you might need to fetch cookies for the correct base address ( Uri.Host
):其次(假设您的cookies
和handler
变量以这种方式初始化),您可能需要为正确的基址( Uri.Host
)获取 cookie:
IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetURI.Host).Cast<Cookie>()
If you are completely unsure, please check with this approach (deep inspection based on reflection) if cookies are set at all, and for which domain they are set.如果您完全不确定,请检查这种方法(基于反射的深度检查)是否设置了 cookie,以及它们是为哪个域设置的。
Just so you guys know, the problem was I hadn't encoded my form data.只是让你们知道,问题是我没有对我的表单数据进行编码。 Changed content to the line below.将内容更改为下面的行。
var content = new FormUrlEncodedContent(formVals);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.