通过在c#net中重置cookie来加载网页

时间:2015-01-16 22:55:15

标签: c# .net httpclient webclient

我想创建一个简单的程序,它加载一个网页(例如webclieant控件),我想在每次加载此页面时重置cookie。我不知道,怎么做,所以也许可以举个例子怎么做? 谢谢你的帮助:))

2 个答案:

答案 0 :(得分:0)

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);
}

答案 1 :(得分:0)

如果要使用Framework的WebClient类进行简单加载,实际上很简单。 WebClient类可以使用Headers和ResponseHeaders属性来使用Cookie。如果要在每个请求中清除cookie,只需在执行请求之前清除正确的标头。我不确切知道这是不是你的问题,所以我将发一个如何使用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");
        }
    }
}