在C#中禁用Cookie,您需要执行以下步骤:
using System.Web.Cookie;
HttpCookieContainer
中的默认行为。在这个类中,重写AddCookie
方法以检查是否设置了Cookie的属性,如Expires
或MaxAge
。如果设置了这些属性,则删除它们,从而实际上禁用了Cookie。public class NoCookieHandler : HttpCookieContainer
{
public override HttpCookieCollection GetCookies(Uri uri, bool ignoreUrl革新)
{
HttpCookieCollection cookies = base.GetCookies(uri, ignoreUrl革新);
if (cookies != null)
{
foreach (HttpCookie cookie in cookies)
{
if (cookie.Expires != DateTime.MinValue && cookie.MaxAge != int.MaxValue)
{
cookie.Expires = DateTime.MinValue;
cookie.MaxAge = -1;
}
}
}
return cookies;
}
}
NoCookieHandler
实例,并将其分配给HttpWebRequest
对象的CookieContainer
属性。HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.example.com");
request.CookieContainer = new NoCookieHandler();
通过这种方式,当您使用此HttpWebRequest
对象发出请求时,它将不会发送或接收任何Cookie。这将有效地禁用Cookie。