Search code examples
c#cloudmicroservicesgoogle-cloud-runihostedservice

C# IHostedService with httpclient request on GCloud Run


I'm programming a microservice to GCloud Run is an C# api with a "BackgroundService : IHostService". It works on localhost, but when on Cloud I recieve this error: "The SSL connection could not be established, see inner exception. System.IO.IOException: Received an unexpected EOF or 0 bytes from the transport stream."

This errors shows when It try to call an endpoint in another api.

BackgroundService.cs

public class BackgroundService : IHostedService, IDisposable
{

private Timer? _rotine;

public Task StartAsync() 
{       
    _rotine = new Timer(Job_Get,null,TimeSpan.FromMinutes(2),TimeSpan.FromMinutes(5));
     return Task.CompletedTask;
}

public Task StopAsync()
{
 _rotine?.Change(Timeout.Infinite, 0);
 return Task.CompletedTask;
}

public void Dispose() {_rotine?.Dispose();}

private async void Job_ListarBases(object? state)
{
 string url;
 string result;
 HttpClientHandler clientHandler;
 HttpClient client;
 Uri uri;
 HttpRequestMessage request;
 Task<HttpResponseMessage> response;

  try
  {
    url = "url/get_something";
    uri = new(url);
    clientHandler = new();
    clientHandler.SslProtocols = SslProtocols.Tls12;
    client = new(clientHandler);
    client.BaseAddress = uri;

    request = new(HttpMethod.Get, "");
    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
    response = client.SendAsync(request);
    result = await response.Result.Content.ReadAsStringAsync();
  }
  catch (Exception e)
  {
    Console.WriteLine(e.Message);
    Console.WriteLine(e.InnerException);
  }
}

}

I created a controller in this microservice with 1 endpoint to call the same enpoint ("url/get_something") using the same code. When I call the endpoint before the BackgroundService do this rotine, the BackgroundService's rotine works.


Solution

  • The problem is the CA certificate and certificates childs.

    I downloaded on browser the certicates and pass the command to install in DockerFile.

    COPY solution/certificates/certificate1.crt 
    /usr/share/ca-certificates
    RUN echo "certicate1.crt" >> /etc/ca-certificates.conf
    RUN update-ca-certificates