我的软件中有一个错误,因为C#HttpWebRequest仅将域的cookie用于直接文件。
例如:
值为XYZ
的Cookie test
的路径为/index.html
,域名为127.0.0.1
。
我想将此Cookie与路径/
一起使用。
我怎么能这样做?
当前方法:
CookieContainer cc = new CookieContainer();
HttpWebRequest request = WebRequest.Create("http://127.0.0.1/index.html") as HttpWebRequest;
request.CookieContainer = cc;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
StreamReader sr = new StreamReader(response.GetResponseStream());
MessageBox.Show(sr.ReadToEnd());
sr.Close();
response.Close();
// No cookies would be sent!
request = WebRequest.Create("http://127.0.0.1/informations.html") as HttpWebRequest;
request.CookieContainer = cc; // cc contains a cookie with path `/index.html` which wouldnt sent to informations.html
response = request.GetResponse() as HttpWebResponse;
sr = new StreamReader(response.GetResponseStream());
MessageBox.Show(sr.ReadToEnd());
sr.Close();
response.Close();
提前感谢!
答案 0 :(得分:1)
这种方式应该有效:
此代码使用从初始请求接收的数据填充cookie容器。 Cookie在根路径上为整个域设置,因此每次请求都会发送Cookie
你能查一下吗?
CookieContainer cc = new CookieContainer();
HttpWebRequest request = WebRequest.Create("http://127.0.0.1/index.html") as HttpWebRequest;
//request.CookieContainer = cc;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
foreach (Cookie cookie in response.Cookies)
{
Cookie newCookie = new Cookie(cookie.Name, cookie.Value, "/", "127.0.0.1");
cc.Add(new Uri("http://127.0.0.1"), cookie);
}
StreamReader sr = new StreamReader(response.GetResponseStream());
MessageBox.Show(sr.ReadToEnd());
sr.Close();
response.Close();