var req = (HttpWebRequest)HttpWebRequest.Create("http://mydomain.com/myservice");
var resp = (HttpWebResponse)req.GetResponse();
var cookies = resp.Cookies;
Console.WriteLine("Cookie count: {0}", cookies.Count);
输出是:
Cookie count: 0
我可以看到使用Charles我的Web服务调用返回cookie。为什么它们不会出现在我的回复的cookie集合中?
答案 0 :(得分:1)
尝试在请求对象中创建CookieContainer
以容纳Cookie:
var req = (HttpWebRequest)HttpWebRequest.Create("http://mydomain.com/myservice");
req.CookieContainer = new CookieContainer();
var resp = (HttpWebResponse)req.GetResponse();
var cookies = resp.Cookies;
Console.WriteLine("Cookie count: {0}", cookies.Count);
来自documentation for the CookieContainer
property的备注部分:
默认情况下,
CookieContainer
为空。 您必须指定CookieContainer
反对该属性有cookie 在Cookies
属性中返回 由...返回的HttpWebResponse
GetResponse
方法。