如何将Cookie名称和值添加到Webclient?

时间:2017-01-07 14:51:59

标签: c# cookies webclient

我需要在具有特定名称和值的webclient中放入2个cookie,这样不仅仅是一个值,而且我有以下代码将cookie添加到带有值的标题但我找不到指定方法的方法cookie的名称

System.Net.WebClient HR = new System.Net.WebClient();
HR.Headers.Add(System.Net.HttpRequestHeader.Cookie, "Cookie1 value");
HR.Headers.Add(System.Net.HttpRequestHeader.Cookie, "Cookie2 value");

1 个答案:

答案 0 :(得分:0)

试试这个:

HttpCookie cookie = new HttpCookie("The Name I Wish"); // Create a cookie and give it a name
cookie.Expires = DateTime.Now.AddDays(30);       // expries in one month
cookie.Value = "Some Value";                          // set value
HttpContext.Response.Cookies.Add(cookie); 

HttpCookie cookie1 = new HttpCookie("The Other unique Name I Wish"); // Create a cookie and give it a name
cookie1.Expires = DateTime.Now.AddDays(20);       // expries in 20 days
cookie1.Value = "Some other value Value";                          // set value
HttpContext.Response.Cookies.Add(cookie1);

要通过WebClient按姓名发送Cookie,您可以按照以下方式编写自己的自定义格式:

wb.Headers.Add(HttpRequestHeader.Cookie, "cookiename=cookievalue"); 

按名称列出多个Cookie:

wb.Headers.Add(HttpRequestHeader.Cookie, 
          "cookiename1=cookievalue1;" +
          "cookiename2=cookievalue2");

原始答案在这里:Multi Cookies Using WebClient