【问题标题】:Load webpage with reseting cookies in c# net在 c# net 中加载带有重置 cookie 的网页
【发布时间】:2015-01-16 22:55:14
【问题描述】:

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

【问题讨论】:

  • 你能对你尝试过的东西进行测试吗?或者您研究过哪些资源?
  • 感谢您的帮助 :) 很抱歉,但我不能投票,但我发现,当我只发送一个获取网站的方法时,它在不重置 cookie 的情况下工作得非常好,但我很感激你的时间。

标签: c# .net httpclient webclient


【解决方案1】:

如果你想使用框架的 WebClient 类进行简单的加载,其实很简单。 WebClient 类可以通过使用 Headers 和 ResponseHeaders 属性来使用 Cookie。如果您想清除每个请求的 cookie,只需在执行请求之前清除正确的 Header。我不知道这是否是你的问题,所以我将发送一个关于如何使用 WebClient 处理 cookie 的示例。我希望它是您正在寻找的。​​p>

您可以使用 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");
        }
    }
}

【讨论】:

    【解决方案2】:
    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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-21
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 2015-07-05
      • 2018-04-18
      相关资源
      最近更新 更多