在 c# net 中加载带有重置 cookie 的网页

Load webpage with reseting cookies in c# net

我想制作一个简单的程序,加载一个网页(例如,到 webclient 控件),我想在每次加载此页面时重置 cookie。我不知道,该怎么做,所以也许可以给我一个如何做的例子? 感谢您的帮助:)

HttpCookie aCookie;
string cookieName;
int limit = Request.Cookies.Count;
for (int i=0; i<limit; i++)
{
    cookieName = Request.Cookies[i].Name;
    aCookie = new HttpCookie(cookieName);
    aCookie.Expires = DateTime.Now.AddDays(-1);
    Response.Cookies.Add(aCookie);
}

如果想使用Framework的WebClientclass做简单的加载,其实很简单。 WebClient class 可以通过 Headers 和 ResponseHeaders 属性使用 Cookie。如果您想在每次请求时清除 cookie,只需在执行请求之前清除正确的 Header。我不知道这是否是你的问题,所以我将发送一个关于如何使用 WebClient 处理 cookie 的示例。希望这就是您要找的。

您可以使用 Headers 属性 轻松地在 WebClient 上设置 cookie,并使用 ResponseCookies 属性 获取必须发回的 Cookie。如果您想管理您的 cookie,请尝试这样做:

class Program
{
    static void Main(string[] args)
    {
        // Put your cookies content here
        string myCookies = "Cookie1=Value; Cookie2=Value";

        // The URL you want to send a request
        string url = "https://www.google.com.br/";

        using (var client = new WebClient())
        {
            // If you want to attach cookies, you can do it 
            // easily using this code.
            client.Headers.Add("Cookie", myCookies);

            // Now you get the content of the response the way 
            // better suits your application.
            // Here i'm using DownloadString, a method that returns
            // the HTML of the response as a System.String.
            // You can use other options, like OpenRead, wich
            // creates a Stream to get the Response content.
            string responseContent = client.DownloadString(url);

            // If you want to save the cookies of the response to
            // use them later, just use the ResponseHeaders property.
            string responseCookies = client.ResponseHeaders["Set-Cookie"];

            // Here is the response of your question (I I'm correct). 
            // If you need to use the same instance of WebClient to make
            // another request, you will need to clear the headers that 
            // are being used as cookies.
            // You can do it easily by using this code.
            client.Headers.Remove("Cookie");
        }
    }
}