我正在使用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
此外,使用
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是相关的,但它实际上并没有回答我的问题。
答案 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的一些灵活性。