微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 我不能在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

In addition,some other headers are also restricted when using a WebClient object. These restricted headers include,but are not limited to the following:

  • Accept
  • Connection
  • Content-Length
  • Expect (when the value is set to “100-continue”)
  • If-Modified-Since
  • Range
  • transfer-encoding

The HttpWebRequest class has properties for setting some of the above headers. If it is important for an application to set these headers,then the HttpWebRequest class should be used instead of the WebRequest class.

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

我知道我可以使用HttpWebRequest,但我不想因为它太多工作(必须做一堆转换,不能只是将内容作为字符串).

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

解决方法

虽然它可能很笨拙,但我选择了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的一些灵活性.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐