📅  最后修改于: 2023-12-03 15:29:46.423000             🧑  作者: Mango
当在C#中进行Web请求时,经常需要处理和发送Cookies信息。本文将介绍如何在WebRequest中处理Cookies。
HttpWebRequest
中设置CookieContainer
属性来实现。HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = new CookieContainer();
request.CookieContainer.GetCookies(uri)
方法获取到与提供的URI相关的所有Cookies。string url = "http://www.example.com/";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = new CookieContainer();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
CookieCollection cookies = request.CookieContainer.GetCookies(new Uri(url));
foreach (Cookie cookie in cookies)
{
Console.WriteLine(cookie.Name + ": " + cookie.Value);
}
string url = "http://www.example.com/";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = new CookieContainer();
Cookie cookie = new Cookie("name", "value");
cookie.Domain = ".example.com";
cookie.Path = "/";
request.CookieContainer.Add(cookie);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
以上是C#中使用WebRequest处理Cookies的方法。请注意,这只是使用WebRequest处理Cookies的一种方法。按需求来选择最适合你的方法。