【问题标题】:.NET HttpRequests using the Windows system Cache.NET HttpRequests 使用 Windows 系统缓存
【发布时间】:2010-10-14 06:32:46
【问题描述】:

我正在使用 WebClient 或 HttpRequest/REsponse 对图像进行 http 调用。

我不确定缓存是如何专门为浏览器工作的,但有没有办法让 WebClient 或 WebHttpRequest 使用浏览器使用的系统“临时 Internet 文件”缓存?

或者,我是否必须编写自己的磁盘缓存器?

【问题讨论】:

    标签: .net windows http caching


    【解决方案1】:

    您可以通过设置 CachePolicy 属性来指示 WebRequest 使用系统缓存。

    以下代码(取自MSDN)将请求缓存一天。缓存存储在当前用户的临时 Internet 文件夹中(至少在 Windows XP 上)。

    // Create a policy that allows items in the cache
    // to be used if they have been cached one day or less.
    HttpRequestCachePolicy requestPolicy = 
      new HttpRequestCachePolicy (HttpCacheAgeControl.MaxAge,
      TimeSpan.FromDays(1));
    
    WebRequest request = WebRequest.Create (resource);
    
    // Set the policy for this request only.
    request.CachePolicy = requestPolicy;
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    
    // Determine whether the response was retrieved from the cache.
    Console.WriteLine ("The response was retrieved from the cache : {0}.",
     response.IsFromCache);
    
    Stream s = response.GetResponseStream ();
    // do something with the response stream
    s.Close();
    response.Close();
    

    【讨论】:

      【解决方案2】:

      如果您正在发出 HTTP 请求,并且您希望您的请求在请求的资源已被请求的情况下访问本地缓存,则您必须编写自己的缓存。

      有许多潜在的实现。这实际上取决于您期望请求多少不同的资源以及频率。

      【讨论】:

      • 谢谢。我刚写完自己的。只花了 5 分钟就得到了一个我满意的 API
      • @Chris:有这方面的文档吗?我不相信这是真的。
      • 我也没有,最糟糕的是 HttpRuntime.Cache
      • @Anthony:你什么意思? .NET 框架没有与 IE 结合。如果有办法,它是 Windows API 或 IE 程序集引用的一部分。
      • 不,不是,但是IE没有实现HTTP协议,这是WinInet做的,还有WinInet的其他客户端。所以问题是 WebClient 是使用 WinInet 堆栈(或模仿它)还是完全独立运行。我怀疑它确实如此。
      猜你喜欢
      • 2011-09-12
      • 2011-09-06
      • 2014-11-27
      • 1970-01-01
      • 1970-01-01
      • 2010-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多