首页 > 解决方案 > 如何从 HttpResponseMessage 中检索 Cookie

问题描述

我在一个我知道返回 cookie 的 post 请求中发送表单数据,但我的 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 容器中

标签: c#cookies.net-core

解决方案


你的问题有一些不清楚的方面:你的cookies变量来自哪里,你的handler变量来自哪里?这些细节对于回答这个问题很重要。

我可以想到您的代码中有两个可能的错误部分。首先,您应该将 a 附加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);

其次(假设您的cookieshandler变量以这种方式初始化),您可能需要获取正确基地址的 cookie ( Uri.Host):

IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetURI.Host).Cast<Cookie>()

如果您完全不确定,请使用这种方法(基于反射的深度检查)检查是否设置了 cookie,以及它们是为哪个域设置的。


推荐阅读