c# - 如何正确添加 WebRequest 标头?
问题描述
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();
}
}
我昨天写了这个,它工作得很好。今天突然这不再起作用了。使用 System.Net.WebRequest 时无法设置一些 HTTP 标头有一个几乎完全相同的问题,但答案https://stackoverflow.com/a/4752359/4427870说我不能使用User-Agent
标头,但我确实在前一天使用过。
我得到的错误:System.ArgumentException: 'The 'User-Agent' header must be modified using the appropriate property or method.
Parameter name: name'
我想使用WebRequest
而不是WebClient
or HttpWebRequest
。
解决方案
您需要UserAgent
直接设置,使用CreateHttp
which returns 代替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
是一个受限制的标头,必须通过属性设置,这里有一个所有受限制标头的列表。
推荐阅读
- mysql - 两个表的mysql并集并对结果进行排序
- javascript - 有条件地渲染导航栏,在 ReactJS 中转换为下拉菜单
- php - 将 [title] 添加到可填充属性以允许在 [App\Post] 上进行批量分配
- go - 如何在字节大小方面比较文本的原始版本和压缩版本
- c# - ASP.NET MVC 路由?// UrlParamter.Optional 与空字符串
- c# - 使用 Swashbuckle Aspnetcore 将 `host`、`basePath` 和 `schemes` 添加到 swagger.json
- r - 闪亮的:反应元素只工作一次?在 gglot2 上设置颜色以保持系列
- git - 在外部硬盘中使用 GitHub Offline 会检测到更改吗?
- java - 为什么 println 方法中的字符串显示两次?
- android - 如果激活分屏,如何全屏打开我的应用程序