Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# ASP.NET Core - SocketException: No such host is known

I am having issues which seem to be related calling a specific API asynchronously using HttpClient - the strange thing is that it doesn't happen all the time and can be solved by refreshing the page (sometimes once, sometimes multiple times).

I thought this could be a local issue but hosting on Azure produces the same results.

Raw exception details:

System.Net.Sockets.SocketException (11001): No such host is known at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)

I have checked:

  • There are no limits imposed on the API
  • Passing the request url in a browser returns the expected JSON result
  • Refreshing the page sometimes resolves the issue

The start of the error: Error top

The rest: Error bottom

This is the method that seems to be causing the issue:

public async Task<List<MoonPhase.Phasedata>> GetPhaseDataAsync(double lat, double lng, int year)
{
    string requestUrl = "https://api.usno.navy.mil/moon/phase?year=" + year + "&coords=" + locationService.FormatCoordinates(lat, lng) + "&tz=0";

    using (var client = new HttpClient())
    {
        var content = await client.GetStringAsync(requestUrl);
        var moonPhaseObject = JsonConvert.DeserializeObject<MoonPhase.RootObject>(content, new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore
        });

        return moonPhaseObject.PhaseData;
    }
}
like image 293
Beau Avatar asked Jun 27 '19 14:06

Beau


1 Answers

I tested the API by attempting to access multiple times within 15 minutes (using this URI). For a minute or two it seemed to have DNS issues.

The GetStringAsync method throws an HttpRequestException exception if there are issues such as DNS failure (source). You could try catching this exception and implementing a retry mechanism if this exception is thrown.

like image 196
zmike Avatar answered Oct 20 '22 17:10

zmike