HttpWebRequest.CookieContainer 获取或设置与此请求关联的 Cookie。默认情况下CookieContainer 是null
。
它是一种数据结构, 它为Cookie类的实例提供存储, 并以类似于数据库的方式访问。 CookieContainer 具有一个容量限制, 该限制是在创建容器或由属性更改时设置的。
Cookie类的实例根据其源 URI 添加到容器中。 它会添加到与 URI CookieCollection关联的内部。 从基于 URI CookieCollection的容器中检索, 或者作为可用于提交 HTTP WebRequests 的字符串从容器中检索。
Cookie 有三个属性, 这些属性控制容器的内容量: Capacity、 MaxCookieSize和PerDomainCapacity。 CookieContainer 这些值分别为300、4096和20的默认设置。 当将Cookie添加到容器时,这些属性用于确定是否应丢弃CookieContainer中已包含的Cookie以便为新容器腾出空间。 Cookie 跟踪每个加法, 以确保Capacity 不会超过或PerDomainCapacity限制。 CookieContainer 如果超过其中一个或两个, Cookie则将删除由CookieContainer保留的实例。 首先, 删除任何Cookie过期的。 如果必须回收更多的容量, 则会清除最近最少使用CookieCollection的空间。
出于安全原因,默认情况下禁用了 cookie。 如果你想要使用 cookie,则使用CookieContainer属性,以便启用 cookie。
下面的代码示例将请求发送到的 URL,并显示在响应中返回的 cookie。
1 using System.Net;
2 using System;
3 namespace Examples.System.Net.Cookies
4 {
5 // 此示例在命令行中运行。
6 // 指定一个参数:发送请求的主机的名称。
7 // 如果请求成功,该示例将显示主机返回的cookie的内容。
8
9 public class CookieExample
10 {
11 public static void Main(string[] args)
12 {
13 if (args == null || args.Length != 1)
14 {
15 Console.WriteLine("Specify the URL to receive the request.");
16 Environment.Exit(1);
17 }
18 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(args[0]);
19 request.CookieContainer = new CookieContainer();
20
21 HttpWebResponse response = (HttpWebResponse) request.GetResponse();
22
23
24
25 // Print the properties of each cookie.
26 foreach (Cookie cook in response.Cookies)
27 {
28 Console.WriteLine("Cookie:");
29 Console.WriteLine("{0} = {1}", cook.Name, cook.Value);
30 Console.WriteLine("Domain: {0}", cook.Domain);
31 Console.WriteLine("Path: {0}", cook.Path);
32 Console.WriteLine("Port: {0}", cook.Port);
33 Console.WriteLine("Secure: {0}", cook.Secure);
34
35 Console.WriteLine("When issued: {0}", cook.TimeStamp);
36 Console.WriteLine("Expires: {0} (expired? {1})",
37 cook.Expires, cook.Expired);
38 Console.WriteLine("Don't save: {0}", cook.Discard);
39 Console.WriteLine("Comment: {0}", cook.Comment);
40 Console.WriteLine("Uri for comments: {0}", cook.CommentUri);
41 Console.WriteLine("Version: RFC {0}" , cook.Version == 1 ? "2109" : "2965");
42
43 // Show the string representation of the cookie.
44 Console.WriteLine ("String: {0}", cook.ToString());
45 }
46 }
47 }
48 }
49
50 // 此示例的输出将根据指定的主机名而有所不同,但将类似于以下内容。
51 /*
52 Cookie:
53 CustomerID = 13xyz
54 Domain: .contoso.com
55 Path: /
56 Port:
57 Secure: False
58 When issued: 1/14/2003 3:20:57 PM
59 Expires: 1/17/2013 11:14:07 AM (expired? False)
60 Don't save: False
61 Comment:
62 Uri for comments:
63 Version: RFC 2965
64 String: CustomerID = 13xyz
65 */
CookieContainer 在 .NET3.5 与 .NET4.0 中的不同
.NET Framework 4.0 中的 HttpWebRequest.CookieContainer 有bug,参考:https://www.crifan.com/baidu_emulate_login_for_dotnet_4_0_error_the_fisrt_two_args_should_be_string_type_0_1/