0
votes

I'm creating a WebAPI in .NetCore 1.1 which needs to call an external service. When I run it with dotnet run it works perfectly, but when I use Docker I get an

One or more errors occurred. (An error occurred while sending the request.)

This is my Post method:

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;
    }
  }
}

The error is thrown in line client.PostAsync. The same error occurs in the GET method.

I already check the URL and the parameters.

What makes it even more intriguing is that it only happens when I run my application inside a docker container. When I run my application without Docker it works very well.

Thanks for your help.

1
You need to go deeper and log the exception. Check it for inner exceptions providing additional info. For now, your description is too broad. 1 possible reason of 1000 - target host is inaccessible from docker network. - Ilya Chumakov
Run what how? You need to provide more information. Commands you are running. What the URL is is posting to. Where this URL is running. Logs for each of the services involved. What Docker version. If Docker is local, how is it installed / running. - Andy Shinn
Sidenote: you're using async method in synchronous way with blocking call .Result, which is bad and dangerous practice. Use await in this case - VMAtm

1 Answers

0
votes

Sorry for the lack of details, but after some reading and Googling I finally discovered the problem.

I had two containers running on localhost so I was requesting a service from the container A to the container B.

I used the http://127.0.0.1:356/api/LogIn address, but the problem is that localhost in this case does not point to my machine, but to the container A itself. That's why I could make it work with dotnet run but not with Docker.

As a matter of fact, this answer made me see my mistake.