我正在尝试获取标头“Set-Cookie”或访问cookie容器,但Set-Cookie标头不可用。 cookie位于响应头中,但它不在客户端请求对象中。 我正在使用
注册ClientHttp
堆栈
bool httpResult = WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
以下是回复:
HTTP/1.1 200 OK
Content-Type: application/xml; charset=utf-8
Connection: keep-alive
Status: 200
X-Powered-By: Phusion Passenger (mod_rails/mod_rack) 3.0.0.pre4
ETag: "39030a9c5a45a24e485e4d2fb06c6389"
Client-Version: 312, 105, 0, 0
X-Runtime: 44
Content-Length: 1232
Set-Cookie: _CWFServer_session=[This is the session data]; path=/; HttpOnly
Cache-Control: private, max-age=0, must-revalidate
Server: nginx/0.7.67 + Phusion Passenger 3.0.0.pre4 (mod_rails/mod_rack)
<?xml version="1.0" encoding="UTF-8"?>
<user>
...
</user>
我的回调代码包含以下内容:
var webRequest = (HttpWebRequest)result.AsyncState;
raw = webRequest.EndGetResponse(result) as HttpWebResponse;
foreach (Cookie c in webRequest.CookieContainer.GetCookies(webRequest.RequestUri))
{
Console.WriteLine("Cookie['" + c.Name + "']: " + c.Value);
}
我也试过查看标题,但响应中也没有Set-Cookie标题。
关于可能出现什么问题的任何建议?
答案 0 :(得分:6)
尝试显式传递新的CookieContainer:
CookieContainer container = new CookieContainer();
container.Add(new Uri("http://yoursite"), new Cookie("name", "value"));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://yoursite");
request.CookieContainer = container;
request.BeginGetResponse(new AsyncCallback(GetData), request);
答案 1 :(得分:2)
您正在接收HttpOnly cookies:
Set-Cookie: _CWFServer_session=[This is the session data]; path=/; HttpOnly
出于安全原因,无法从代码访问这些cookie,但您仍可以在下次调用HttpWebRequest时使用它们。更多相关信息:Reading HttpOnly Cookies from Headers of HttpWebResponse in Windows Phone
使用WP7.1,我在阅读非HttpOnly cookie时也遇到了问题。我发现如果HttpWebRequest的响应来自缓存,它们就不可用。使用随机数使查询唯一可以解决缓存问题:
// The Request
Random random = new Random();
// UniqueQuery is used to defeat the cache system that destroys the cookie.
_uniqueQuery = "http://my-site.somewhere?someparameters=XXX"
+ ";test="+ random.Next();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_uniqueQuery);
request.BeginGetResponse(Response_Completed, request);
获得响应后,您可以从响应标头中获取cookie:
void Response_Completed(IAsyncResult result)
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
String header = response.Headers["Set-Cookie"];
我从来没有设法让CookieContainer.GetCookies()方法起作用。
答案 2 :(得分:0)
cookie是否为httponly?如果是这样,您将无法看到它,但如果您为第二个请求使用相同的CookieContainer,请求将包含cookie,即使您的程序将无法看到它。
答案 3 :(得分:-1)
您必须直接编辑标题集合。像这样:
request.Headers["Set-Cookie"] = "name=value";
request.BeginGetResponse(myCallback, request);