C#ASP.NET Core-SocketException:尚无此类主机 [英] C# ASP.NET Core - SocketException: No such host is known

查看:98
本文介绍了C#ASP.NET Core-SocketException:尚无此类主机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的问题似乎与使用 HttpClient 异步调用特定的API有关-奇怪的是,它不会一直发生,并且可以通过刷新页面来解决(有时一次,有时是多次).

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).

我认为这可能是本地问题,但是在Azure上托管会产生相同的结果.

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

原始异常详细信息:

System.Net.Sockets.SocketException(11001):尚无此类主机在System.Net.Http.ConnectHelper.ConnectAsync(字符串主机,Int32端口,CancelationToken cancelToken)

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

我已检查:

  • API上没有限制
  • 在浏览器中传递请求url返回预期的JSON结果
  • 刷新页面有时可以解决问题

错误的开始:

其余:

这似乎是导致问题的方法:

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

推荐答案

我通过尝试在15分钟内多次访问来测试了API(使用

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.

如果存在DNS失败之类的问题,则 GetStringAsync 方法将引发 HttpRequestException 异常(

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.

这篇关于C#ASP.NET Core-SocketException:尚无此类主机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆