我不能在WebClient上设置If-Modified-Since吗?

时间:2015-04-06 02:55:43

标签: c# httpwebrequest webclient if-modified-since

我正在使用WebClient来检索网站。我决定设置If-Modified-Since,因为如果网站没有更改,我不想再次获取它:

var c = new WebClient();
c.Headers[HttpRequestHeader.IfModifiedSince] = Last_refreshed.ToUniversalTime().ToString("r");

其中Last_refreshed是一个变量,用于存储我上次浏览网站的时间。

但是当我运行这个时,我得到一个WebException的文字:

The 'If-Modified-Since' header must be modified using the appropriate property or method.
Parameter name: name

原来API docs mention this

  

此外,使用WebClient对象时,其他一些标题也会受到限制。这些受限制的标题包括但不限于以下内容:

     
      
  • 接受
  •   
  • 连接
  •   
  • 的Content-Length
  •   
  • 期望(当值设置为" 100-continue")
  •   
  • 如果-Modified-Since的
  •   
  • 范围
  •   
  • 传送编码
  •   
     

HttpWebRequest类具有用于设置上述某些标头的属性。如果应用程序设置这些标头很重要,则应使用HttpWebRequest类而不是WebRequest类。

这是否意味着无法从WebClient设置它们?为什么不?在正常If-Modified-Since中指定HTTP GET有什么问题?

我知道我可以使用HttpWebRequest,但我不想这样做,因为它的工作太多(必须做一堆演员,不能只是得到内容为字符串)。

此外,我知道Cannot set some HTTP headers when using System.Net.WebRequest是相关的,但它实际上并没有回答我的问题。

1 个答案:

答案 0 :(得分:1)

尽管可能很笨重,但我选择了子类WebClient,以便以模仿WebClient通常工作方式的方式添加功能(其中头文件被/ reset消耗掉)每次使用):

public class ApiWebClient : WebClient {
  public DateTime? IfModifiedSince { get; set; }

  protected override WebRequest GetWebRequest(Uri address) {
    var webRequest = base.GetWebRequest(address);
    var httpWebRequest = webRequest as HttpWebRequest;
    if (httpWebRequest != null) {
      if (IfModifiedSince != null) {
        httpWebRequest.IfModifiedSince = IfModifiedSince.Value;
        IfModifiedSince = null;
      }
      // Handle other headers or properties here
    }
    return webRequest;
  }
}

这样做的好处是不必为WebClient提供的标准操作编写样板文件,同时仍然提供了使用WebRequest的一些灵活性。