C# 如何正确添加WebRequest标头?

C# 如何正确添加WebRequest标头?,c#,.net,webrequest,C#,.net,Webrequest,我昨天写的,效果很好。今天突然间,这一切都不起作用了。有一个几乎完全相同的问题,但答案是我不能使用用户代理标题,但我确实在前一天使用了它 我得到的错误:System.ArgumentException:“必须使用适当的属性或方法修改“用户代理”头。 参数名称:名称“ 我想使用WebRequest而不是WebClient或HttpWebRequest您需要直接设置UserAgent,使用返回HttpWebRequest的代理,然后您可以执行以下操作: var webRequest = WebReq

我昨天写的,效果很好。今天突然间,这一切都不起作用了。有一个几乎完全相同的问题,但答案是我不能使用
用户代理
标题,但我确实在前一天使用了它

我得到的错误:
System.ArgumentException:“必须使用适当的属性或方法修改“用户代理”头。
参数名称:名称“


我想使用
WebRequest
而不是
WebClient
HttpWebRequest

您需要直接设置
UserAgent
,使用返回
HttpWebRequest
的代理,然后您可以执行以下操作:

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();
    }
}

UserAgent
是一个受限头,必须通过属性进行设置,有一个所有受限头的列表。

您需要直接设置
UserAgent
,使用返回
HttpWebRequest
,然后您可以执行以下操作:

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();
    }
}
UserAgent
是一个受限头,必须通过属性进行设置,有一个所有受限头的列表