HttpClient socket exception



我试图从我的web API调用托管在azure上的一些外部API。API在我的本地机器上工作得很好,但是当我在服务器上部署它时,它开始抛出System.Net.Sockets.SocketException(10060)。由于被连接方在一段时间后没有正确响应,或者由于连接的主机没有响应,导致连接尝试失败。虽然我已将请求超时时间增加到5分钟,但连接在21秒后静静地停止并抛出上述异常。

下面是我的代码:
var telemetries = new TelemetryResponse();
var client = httpClientFactory.CreateClient("Lynx");
client.Timeout = TimeSpan.FromMinutes(5);
var httpResponseMessage = await client.GetAsync("vehicletelemetries/All?key=iLJIbAVXOnpKz5xyF0zV44yepu5OVfmZFhkHM7x");
if (httpResponseMessage.IsSuccessStatusCode)
{
string content = await httpResponseMessage.Content.ReadAsStringAsync();
telemetries = JsonConvert.DeserializeObject<TelemetryResponse>(content);
}

我得到的异常是:

System.Net.Sockets。SocketException(10060):连接尝试失败,因为被连接的一方在一段时间后没有正确响应,或者由于连接的主机没有响应而建立连接失败。在System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs。抛出异常(SocketError error, CancellationToken)在System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource。GetResult (Int16令牌)在System.Net.Sockets.Socket。__waitforconnectwithcancel |277_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken CancellationToken)在System.Net.Http.HttpConnectionPool。ConnectToTcpHostAsync(字符串主机,Int32端口,HttpRequestMessage initialRequest,布尔async, CancellationToken CancellationToken)

大家好,罪魁祸首是代理,我们必须配置我们的HttpClient代理,同时在DI容器中创建/注册它。我已经像这样在DI中注册了HttpClient。

var proxySettings = new ProxySetting();
Configuration.Bind(nameof(ProxySetting), proxySettings);
services.AddHttpClient("Lynx", client =>
{
client.BaseAddress = new Uri(Configuration.GetSection("LynxUrl").Value);
}).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { Proxy = new MyProxy(proxySettings)});

代理代码是

public class MyProxy : IWebProxy
{
private readonly ProxySetting _proxySetting;
public MyProxy(ProxySetting proxySetting)
{
_proxySetting = proxySetting;
}
public ICredentials Credentials
{
//get { return new NetworkCredential("username", "password"); }
get { return new NetworkCredential(_proxySetting.UserName, _proxySetting.Password,_proxySetting.Domain); }
set { }
}
public Uri GetProxy(Uri destination)
{
return new Uri(_proxySetting.ProxyUrl);
}
public bool IsBypassed(Uri host)
{
return false;
}

}

我的问题完全解决了。

你得到一个错误代码:

WSAETIMEDOUT10060

连接超时。连接尝试失败,因为被连接方在一段时间后没有正确响应,或者已建立的连接失败,因为连接的主机未能响应。

https://learn.microsoft.com/en-us/windows/win32/winsock/windows-sockets-error-codes-2 WSAETIMEDOUT

检查你的网络连接,ip地址,端口,也许连接被防火墙阻止了。

最新更新