自动 Cookie 处理 C#/.NET HttpWebRequest+HttpWebResponse

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/571964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 08:43:48  来源:igfitidea点击:

Automatic Cookie Handling C#/.NET HttpWebRequest+HttpWebResponse

c#.netcookies

提问by

Is there any way to automatically handle cookies in .NET with the HttpWebRequest/HttpWebResponse objects? I'm preferably looking for an equivalent to LWP::UserAgent and its behaviour (perl), only in a .NET environment.

有没有办法在 .NET 中使用 HttpWebRequest/HttpWebResponse 对象自动处理 cookie?我最好只在 .NET 环境中寻找与 LWP::UserAgent 及其行为 (perl) 等效的东西。

Any suggestions or advice?

有什么建议或意见吗?

采纳答案by Dan Herbert

I think what you're looking for is the CookieContainerclass. If I understand what you're trying to do correctly, you have separate objects for request & response, and you want to transfer the responsecookie collection into the next requestcookie collection automatically. Try using this code:

我认为您正在寻找的是CookieContainer类。如果我理解您要正确执行的操作,则您有单独的请求和响应对象,并且您希望将响应cookie 集合自动传输到下一个请求cookie 集合中。尝试使用此代码:

CookieContainer cookieJar = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com");
request.CookieContainer = cookieJar;

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
int cookieCount = cookieJar.Count;

Once you create a cookieJarand set it to the request's CookieContainer, it will store any cookies that come from the response, so in the example above, the cookie jar's count will be 1once it visits Google.com. The cookie container properties of the request & response above will store a pointer to the cookieJar, so the cookies are automatically handled and shared between the objects.

创建一个cookieJar并将其设置为请求的 CookieContainer 后,它将存储来自响应的所有 cookie,因此在上面的示例中,cookie jar 的计数将是1它访问 Google.com 的一次。上面请求和响应的 cookie 容器属性将存储一个指向 cookieJar 的指针,因此 cookie 会自动处理并在对象之间共享。