【问题标题】:Is there a way to clear a CookieContainer?有没有办法清除 CookieContainer?
【发布时间】:2016-01-06 15:38:28
【问题描述】:

我想清除 CookieContainer 中收到的所有 cookie,而无需初始化新的 CookieContainer、HttpClientHandler 和 HttpClient。有办法吗?我检查了MSDN,但似乎我只能使用 GetCookies(Uri) 来获取与特定 Uri 关联的所有 cookie。

var cc = new CookieContainer();

var handler = new HttpClientHandler
    {
        CookieContainer = cc
    };

var client = new HttpClient(handler);

【问题讨论】:

  • 看来您需要使用反射。创建新的 HttpClient 有什么问题? stackoverflow.com/questions/15983166/…
  • @dana:我只是觉得这可能会浪费资源,因为我正在使用多个任务。
  • 就个人而言,如果替代方法是使用反射来闯入私有成员,我不会担心创建更多类的实例。尤其如此,因为您已经通过 HTTP 发出网络请求。

标签: c# cookies httpclient


【解决方案1】:

我知道的唯一解决方案是让所有 cookie 过期:

        cc.GetCookies(new Uri(...))
            .Cast<Cookie>()
            .ToList()
            .ForEach(c => c.Expired = true);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    相关资源
    最近更新 更多