我试图从我的web中调用一些托管在azure上的外部Api。API在我的本地计算机上运行良好,但当我将它部署到服务器上时,它开始抛出System.Net.Sockets.SocketException (10060).A连接尝试失败,原因是连接方在一段时间后没有正确响应,或者已建立的连接由于连接主机未能响应而失败。虽然我已经将请求超时增加到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.ThrowException(SocketError错误,System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16令牌( CancellationToken cancellationToken) )( System.Net.Sockets.Socket.g__WaitForConnectWithCancellation|277_0(AwaitableSocketAsyncEventArgs saea,ValueTask connectTask,CancellationToken cancellationToken) ( System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String主机),Int32端口,HttpRequestMessage initialRequest,布尔异步,CancellationToken cancellationToken) )
发布于 2022-06-10 06:22:41
嗨,伙计们,罪魁祸首是代理,我们必须使用代理配置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;
}
}
它彻底解决了我的问题。
发布于 2022-06-08 09:50:56
您有一个错误代码:
WSAETIMEDOUT 10060
连接超时。连接尝试失败是因为连接方在一段时间后没有正确响应,或者建立的连接失败是因为连接主机没有响应。
https://learn.microsoft.com/en-us/windows/win32/winsock/windows-sockets-error-codes-2#WSAETIMEDOUT
检查您的网络连接,ip入口,端口,也许连接被防火墙阻塞。
https://stackoverflow.com/questions/72543538
复制相似问题