System.Net.Http.HttpRequestException: 设备未配置 ---> System.Net.Sockets.SocketException: 设备未配置

5

System.Net.Http.HttpRequestException: 设备未配置 ---> System.Net.Sockets.SocketException: 设备未配置

当我尝试从自定义中间件为aspnet core web应用程序发出网络请求时,会收到上述错误。该错误发生在以下代码块的第四行:

var web = new WebClient();
var testing = _configuration.GetSection("IPStack")["AccessKey"];
web.QueryString.Add("access_key", _configuration.GetSection("IPStack")["AccessKey"]);
string ipstackRaw = web.DownloadString($"http://api.ipstack/{ipaddress}");

我正在使用Mac上的Visual Studio,社区版。是什么导致了这个错误?
更新
自从原帖发布以来,我尝试了几个方法但都没有成功。以下是我尝试过的内容:
- 在我的PC(Windows 10)上使用Visual Studio专业版运行应用程序 - 使用HttpClient尝试请求 - 在中间件之外尝试请求

我在我的 Mac 上遇到了同样的错误,同时我的机器上的互联网也停止工作了。一分钟后它又开始工作了,我的测试也是如此。看起来像是 Mac 的问题。 - Joe Phillips
2个回答

5

请确保正确输入请求URI。

更改
string ipstackRaw = web.DownloadString($"http://api.ipstack/{ipaddress}");

string ipstackRaw = web.DownloadString($"http://api.ipstack.com/{ipaddress}");


当主机不存在且DNS解析失败时也会发生这种情况。我花了一段时间才弄清楚这个问题。 - galdin

1
我建议您使用HttpWebRequest来完成它。
   string apiKey = "YOUR_ACCESS_KEY";
        var request = (HttpWebRequest)WebRequest.Create("https://api.ipstack.com/134.201.250.155?access_key="+ apiKey);
        request.Method = "GET";
        request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36";
        request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
        request.Headers.Add("accept-language", "en,hr;q=0.9");
        request.Headers.Add("accept-encoding", "");
        request.Headers.Add("Upgrade-Insecure-Requests", "1");
        WebResponse response = request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
        string responseFromServer = reader.ReadToEnd();
        reader.Close();
        response.Close();

我会看看它是否修复了问题,但是HttpWebRequest已经被弃用 - Corey P

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接