为什么Response.Cookies为空?

时间:2015-09-29 09:20:42

标签: c# cookies web

当我运行这个python脚本时

import requests

main_page_request = requests.get("http://carkit.kg/")
cookie = main_page_request.cookies.get("csrftoken", "")

我得到了正确的结果,但是当我在C#上运行此代码时:

string url = @"http://carkit.kg";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Debug.Log(response.Cookies["csrftoken"]); // prints "Null"

它说响应.Cookies是空的。有什么问题?

1 个答案:

答案 0 :(得分:2)

您必须在请求中添加Cookie容器。然后它返回cookie:

CookieContainer c = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = c;

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Console.WriteLine(response.Cookies["csrftoken"]);
// prints "csrftoken=E1iRIi7cQvxvJcnSgOgaEP3XPxTHRUfT"