简体   繁体   English

如何在HttpWebRequest中获取由“ Set-Cookie”设置的cookie?

[英]How can I get the cookies set by “Set-Cookie” in a HttpWebRequest?

I was hoping the following code would yield a non-zero value: 我希望以下代码产生一个非零值:

var webRequest = (HttpWebRequest) WebRequest.Create(loginUrl);
var webResponse = (HttpWebResponse)webRequest.GetResponse();
Console.WriteLine(webResponse.Cookies.Count);

yet no cookies seem to show up in webRespone.Cookies . 但是似乎没有cookie出现在webRespone.Cookies I'm positive the cookies are there, as I'm sniffing the data with Fiddler. 我很肯定Cookie在那里,因为我正在用Fiddler嗅探数据。 This is the response I'm getting: 这是我得到的答复:

HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/7.5
Set-Cookie: __Abc=Def; path=/; HttpOnly
PS-ResponseTime: 00:00:00.0624001
PS-Build: 2013-03-19-11-36-59
PS-Node: 02
Date: Tue, 19 Mar 2013 21:14:51 GMT
Content-Length: 57872

Does it have anything to do with the fact the cookie is HttpOnly ? 它与Cookie是否为HttpOnly吗?

Edit 编辑

It's seems I can get them through HttpWebRequest 's CookieContainer which is certainly useful if I intend to proceed to a sequence of requests/responses. 看来我可以通过HttpWebRequestCookieContainer来获取它们,如果我打算继续执行一系列请求/响应,那肯定很有用。 But why can't I access them the same through the HttpWebResponse.Cookies field, anyway? 但是为什么无论如何我还是不能通过HttpWebResponse.Cookies字段访问它们?

Thanks 谢谢

You're right, you'll need to hand the request an instance of CookieContainer and then reference that instance to see the cookies. 没错,您需要向请求提交一个CookieContainer实例,然后引用该实例以查看Cookie。 Basically, HttpWebResponse does not directly expose cookies on the response that are marked as HttpOnly. 基本上,HttpWebResponse不会在响应上直接公开标记为HttpOnly的cookie。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM