0

I have a custom class contained in a standard .net class library which makes a request to an external public facing api using the HttpClient.

When I instantiate the class and call the method via a standard .net console app, the expected result is returned.

However, executing the same code via a Xunit test produces the following exception:

'The underlying connection was closed: An unexpected error occurred on a send.'

Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

Both the test project and class library project framework are .Net Standard 4.8.

Most examples online make use of the WebApplicationFactory, documented here. In my case I am not using ASP Core and I cannot use this class.

I am not that experienced in xunit and there is not much detail in the error message as to why this is occuring.

To try isolate the issue I tried running this piece of code directly in the test method and the same error occurrs.

Any suggestions/work arounds are much appreciated.

using (HttpClient httpClient = new HttpClient())
{
    var request = new HttpRequestMessage()
        {
            Method = HttpMethod.Get,
            RequestUri = endpoint
        };
     
        request.Headers.Add("api-key", key);
        using (HttpResponseMessage response = httpClient.SendAsync(request).Result)
        {
            var rawResponse = response.Content.ReadAsStringAsync().Result;
                var response = JsonConvert.DeserializeObject<CustomResponse>(rawResponse);
        }
}
noobie
  • 2,427
  • 5
  • 41
  • 66
  • Have you checked if the valid endpoint is provided before making the api call? – Soundar Anbu Jan 05 '22 at 06:26
  • yes, the exact same parameters are passed that I use in the console app. When executing from the console app it works, executing from the unit test it fails. Even when hard coding the endpoint and key values in the method itself. – noobie Jan 05 '22 at 06:26

1 Answers1

0

I resolved the issue thanks to this post

Adding TLS 1.1 and 1.2 before the request was made worked

ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
noobie
  • 2,427
  • 5
  • 41
  • 66