c# - 如何从 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 容器中
解决方案
你的问题有一些不清楚的方面:你的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);
其次(假设您的cookies
和handler
变量以这种方式初始化),您可能需要获取正确基地址的 cookie ( Uri.Host
):
IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetURI.Host).Cast<Cookie>()
如果您完全不确定,请使用这种方法(基于反射的深度检查)检查是否设置了 cookie,以及它们是为哪个域设置的。
推荐阅读
- java - 将变量作为方法参数传递
- firebase - 不存在文档的 Firestore 事务锁定行为
- angular - Angular 8:路由双嵌套命名路由器出口
- ruby-on-rails - 在多个表的属性中创建搜索
- python-3.x - 有没有更好的方法来做到这一点我有一个工作代码,但我认为它可以优化?
- javascript - 在 promise 函数中等待
- angular - 更改检测器参考不适用于 Angular Material 对话框
- string - 当我已经将对象的内容打印到控制台时,为什么我的字符串流给我空
- solr - 需要有关 Vagrant 托管 Solr 实例的故障排除建议
- math - 将十进制度转换为度分,然后转换为小数秒