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:
那么这是否意味着无法从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的一些灵活性. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |