我的饼干在哪里?

时间:2011-07-06 14:04:16

标签: c# asp.net web-services

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集合中?

1 个答案:

答案 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方法。