Where are my cookies?
var req = (HttpWebRequest)HttpWebRequest.Create("http://mydomain.com/myservice");
var resp = (HttpWebResponse)req.GetResponse();
var cookies = resp.Cookies;
Console.WriteLine("Cookie count: 开发者_StackOverflow社区{0}", cookies.Count);
Output is:
Cookie count: 0
I can see using Charles that the call to my web service is returning cookies. Why don't they show up in my response's cookie collection?
Try creating a CookieContainer
in your request object to accomodate the cookies:
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);
From the Remarks section of the documentation for the CookieContainer
property:
CookieContainer
is null by default. You must assign aCookieContainer
object to the property to have cookies returned in theCookies
property of theHttpWebResponse
returned by theGetResponse
method.
精彩评论