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

夙愿已清 提交于 2021-02-20 09:11:37

问题


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:

The rest:

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

回答1:


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.




回答2:


What? these comments are not completely right, have you read the docs? If you are using Httpclient in net core, you should be using a HttpFactory or a named or typed client.

Using a factory for example

services.AddHttpClient();

And then

public class BasicUsageModel : PageModel
{
    private readonly IHttpClientFactory _clientFactory;

    public IEnumerable<GitHubBranch> Branches { get; private set; }

    public bool GetBranchesError { get; private set; }

    public BasicUsageModel(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }

    public async Task OnGet()
    {
        var request = new HttpRequestMessage(HttpMethod.Get, 
            "https://api.github.com/repos/aspnet/AspNetCore.Docs/branches");
        request.Headers.Add("Accept", "application/vnd.github.v3+json");
        request.Headers.Add("User-Agent", "HttpClientFactory-Sample");

        var client = _clientFactory.CreateClient();

        var response = await client.SendAsync(request);

        if (response.IsSuccessStatusCode)
        {
            Branches = await response.Content
                .ReadAsAsync<IEnumerable<GitHubBranch>>();
        }
        else
        {
            GetBranchesError = true;
            Branches = Array.Empty<GitHubBranch>();
        }                               
    }
}

There are also named clients and typed clients. Try to use those instead your HttpClient directly, this also help with the DNS cache problems.



来源:https://stackoverflow.com/questions/56793682/c-sharp-asp-net-core-socketexception-no-such-host-is-known

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!