C# HttpWebRequest和Cookie处理

C# HttpWebRequest和Cookie处理,c#,asp.net,cookies,httpwebrequest,C#,Asp.net,Cookies,Httpwebrequest,发送从httpwebrequest收到的cookie不会给出正确的结果,但如果我从浏览器cookie复制粘贴cookie值,则返回正确的结果。为什么我不能从httpwebrequest中得到结果,但可以从浏览器中完美地工作 CookieContainer cookieContainer = new CookieContainer(); var targetUri = new Uri("URL1"); HttpWebRequest myHttpWebRequest = (HttpWebReque

发送从httpwebrequest收到的cookie不会给出正确的结果,但如果我从浏览器cookie复制粘贴cookie值,则返回正确的结果。为什么我不能从httpwebrequest中得到结果,但可以从浏览器中完美地工作

CookieContainer cookieContainer = new CookieContainer();

var targetUri = new Uri("URL1");
HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(targetUri);
myHttpWebRequest.Method = "GET";
myHttpWebRequest.CookieContainer = cookieContainer;

//Get Response
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

//Create Request
targetUri = new Uri("URL2");
myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(targetUri);
myHttpWebRequest.Method = "GET";
myHttpWebRequest.CookieContainer = cookieContainer;

//Get Response
myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

using (StreamReader reader = new StreamReader(myHttpWebResponse.GetResponseStream()))
{
   string html = reader.ReadToEnd();
}
以下是通过第一个请求(URL1)接收到cookie的第二个请求(URL2)fiddler:

现在,如果我在浏览器中复制粘贴第一个url(URL1),并使用浏览器中的cookie值,则返回正确的结果:

Request:

GET URL2 
HTTP/1.1
Host: www.xyz.com
Cookie: JSESSIONID=PPPHJwmKQNh2ykVXytlcfTDH2YWNbtv76vPBzZTG3Dfdm9Mx0J74!-876337174

Response:
HTTP/1.1 200 OK
Date: Fri, 27 Feb 2015 13:06:15 GMT
Content-Type: text/html;charset=UTF-8
X-Powered-By: Servlet/2.5 JSP/2.1
Content-Length: 21417

Weblogic将在响应中返回cookies,您需要在下一个请求中将其发送回

cookieContainer.Add(response.Cookies);
(您的cookieContainer在您的机器上,并且是空的)

cookieContainer.Add(response.Cookies);