加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 22:12:32 所属栏目:百科 来源:网络整理
导读:我正在使用WebClient来检索网站.我决定设置If-Modified-Since因为如果网站没有改变,我不想再得到它: var c = new WebClient();c.Headers[HttpRequestHeader.IfModifiedSince] = Last_refreshed.ToUniversalTime().ToString("r"); Last_refreshed是一个变量,
我正在使用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的一些灵活性.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读