在C#中禁用Cookie,您需要執(zhí)行以下步驟:
using System.Web.Cookie;
HttpCookieContainer
中的默認(rèn)行為。在這個(gè)類中,重寫AddCookie
方法以檢查是否設(shè)置了Cookie的屬性,如Expires
或MaxAge
。如果設(shè)置了這些屬性,則刪除它們,從而實(shí)際上禁用了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
實(shí)例,并將其分配給HttpWebRequest
對(duì)象的CookieContainer
屬性。HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.example.com");
request.CookieContainer = new NoCookieHandler();
通過這種方式,當(dāng)您使用此HttpWebRequest
對(duì)象發(fā)出請(qǐng)求時(shí),它將不會(huì)發(fā)送或接收任何Cookie。這將有效地禁用Cookie。