我需要在具有特定名称和值的网络客户端中放置 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");
试试这个:
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");
原始答案在这里: 使用网络客户端的多饼干