Skip to main content
 首页 » 编程设计

c#之如何正确添加 WebRequest header

2024年02月04日30落叶无声

var webRequest = WebRequest.Create("https://vtopbeta.vit.ac.in/vtop/"); 
webRequest.Method = "GET"; 
webRequest.Timeout = 12000; 
webRequest.Headers.Add("User-Agent", 
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"); 
string jsonResponse; 
using (var s = webRequest.GetResponse().GetResponseStream()) 
{ 
    using (var sr = new StreamReader(s ?? throw new InvalidOperationException())) 
    { 
        jsonResponse = sr.ReadToEnd(); 
    } 
} 

我昨天写的,效果很好。今天突然这不再起作用了。有一个几乎准确的问题Cannot set some HTTP headers when using System.Net.WebRequest但答案https://stackoverflow.com/a/4752359/4427870说我不能使用 User-Agent header ,但我确实在一天前使用过它。

我得到的错误:System.ArgumentException: 'The 'User-Agent' header must be modified using the appropriate property or method. 参数名称:name'

我想使用 WebRequest 而不是 WebClient 或 HttpWebRequest。

请您参考如下方法:

需要直接设置UserAgent,使用CreateHttp而不是返回 HttpWebRequest,那么你可以这样做:

webRequest.UserAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"; 

UserAgent 是一个受限 header ,必须通过属性设置,有一个所有受限 header 的列表 here .