首页 > 解决方案 > c# 永久设置 WebClient 用户代理

问题描述

我正在使用 WebClient 向 github api 发送一些请求。

var wc = new WebClient();
wc.Headers.Add("user-agent", "notempty"); 
wc.Headers.Add("authorization", "basic " + Convert.ToBase64String("user:password"));
var response = wc.DownloadString(url + "/labels");
...
var response = wc.DownloadString(url + "/issues");

首先我查询所有标签,然后查询所有问题

但是在第二次 DownloadString 我得到以下异常:

未处理的异常:System.Net.WebException:服务器违反了协议。Section=ResponseStatusLine at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request) at System.Net.WebClient.DownloadString(Uri address)

如果我在第一个 DownloadString 之后设置用户代理,我不会得到异常。这是为什么?

标签: c#.netwebclient

解决方案


推荐阅读