DiluzFerz
DiluzFerz

Reputation: 53

How to resolve System.Net.Http.WinHttpException: A connection with the server could not be established?

In my .Net core API project, when calling another API (which is stopped), I'm getting below error.

System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.Http.WinHttpException: A connection with the server could not be established

Instead of getting this error, I think it should return status code 503 (service unavailable) or 404 (not found), but I'm getting above exception. Please advice how to resolve this? My code is:

HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("apiBaseUrl");
HttpResponseMessage response = await httpClient.GetAsync("apiUrl");

Upvotes: 1

Views: 5973

Answers (1)

Simply Ged
Simply Ged

Reputation: 8672

Welcome to SO.

For your code to get a 503 or 404 response there would need to be a server at the URL you have specified. In your case there is no server at apiBaseUrl to return a HTTP status code. That would be the same for any URL that does not exist.

If you try a different URL e.g. https://google.com/fake, you will get a 404 because the server google.com exists to be able to send back a 404 to say the /fake part was not found on its server.

If you want to handle it then you can catch the System.Net.Http.HttpRequestException and handle that accordingly.

try
{
    HttpClient httpClient = new HttpClient();
    httpClient.BaseAddress = new Uri("apiBaseUrl");
    HttpResponseMessage response = await httpClient.GetAsync("apiUrl");
}
catch(HttpRequestException ex)
{
    // Handle the exception here
}

If you think of it like a postal address. If you write to a random address that doesn't exist then you you will get your letter back from the post office with an exception saying "no such address" - which is equivalent to your exception above.

However, if you write to a real address but to a person that doesn't live there then you will get your letter back from the residents of that address saying "No such person at this address" which is the same as a 404.

In the example, the post office is the .NET Framework/HttpClient class and the residents at the real address are a web server.

Upvotes: 2

Related Questions