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

时间:2019-02-16 19:26:11

标签: c# visual-studio asp.net-core httprequest middleware

  

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

当我尝试从自定义中间件向aspnet核心Web应用程序发出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
  • 尝试请求
  • 在中间件之外尝试请求

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:1)

确保正确键入请求URI。

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

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