.NetCore PostAsync和GetAsync不适用于Docker

时间:2017-05-09 14:57:33

标签: c# docker asp.net-core .net-core

我在.NetCore 1.1中创建了一个需要调用外部服务的WebAPI。当我使用dotnet run运行它时效果很好,但是当我使用 Docker 时,我得到了一个

  

发生了一个或多个错误。 (发送时发生错误   请求。)

这是我的Post方法:

public static string Post(string url, string jsonObject, string serviceName)
{
  // opening a connection to the microservice
  using (HttpClient client = new HttpClient())
  using (HttpResponseMessage response = client.PostAsync(url, new StringContent(jsonObject, Encoding.UTF8, "application/json")).Result)
  {
    LogWrapper.SafeInfo(LoggingEvents.SERVICECALLER_GETSERVICESRESPONSE, "Let's test if we get an OK response from " + serviceName);
    // we'll throw an exception in case status code is different from 200
    response.EnsureSuccessStatusCode();

    LogWrapper.SafeInfo(LoggingEvents.SERVICECALLER_GETSERVICESRESPONSE, "We got an OK response from " + serviceName);

    using (HttpContent responseContent = response.Content)
    {
      return responseContent.ReadAsStringAsync().Result;
    }
  }
}

错误在行client.PostAsync中引发。 GET方法中出现相同的错误。

我已经检查了网址和参数。

更令人感兴趣的是,只有当我在docker容器中运行我的应用程序时才会发生这种情况。当我在没有Docker的情况下运行我的应用程序时,它运行得非常好。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

很抱歉缺乏细节,但经过一些阅读和谷歌搜索后我终于发现了问题。

我在 localhost 上运行了两个容器,所以我要求从容器A到容器B的服务。

我使用了http://127.0.0.1:356/api/LogIn地址,但问题是在这种情况下localhost不指向我的机器,而是指向容器A本身。这就是为什么我可以使用dotnet run但不能使用Docker

事实上,this answer让我看到了我的错误。