【问题标题】:System.Net.Http.HttpRequestException: Device not configured ---> System.Net.Sockets.SocketException: Device not configuredSystem.Net.Http.HttpRequestException:设备未配置---> System.Net.Sockets.SocketException:设备未配置
【发布时间】:2019-02-16 19:26:11
【问题描述】:

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 尝试请求
  • 在中间件之外尝试请求

【问题讨论】:

  • 我的 Mac 上出现了同样的错误,同时我的互联网停止在这台机器上工作。一分钟后它又开始工作了,我的测试也是如此。好像是 Mac 问题

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


【解决方案1】:

确保您正确键入请求 URI。

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

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

【讨论】:

  • 主机不存在且DNS解析失败时也会发生。我花了一段时间才弄清楚这一点。
【解决方案2】:

我建议你使用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 一直是deprecated
猜你喜欢
  • 1970-01-01
  • 2011-12-21
  • 1970-01-01
  • 2017-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多