我有一个简单的 web api,它获取一个 url,并生成一个短数字作为短 url。我创建了一个 VS 控制台应用程序,我通过 HTTPClient
调用 web api目的。当我第一次运行代码时,它抛出以下错误:
Error message: One or more errors occurred.
InnerException: System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult) at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult) --- End of inner exception stack trace --- at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult) at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar) --- End of inner exception stack trace --- at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult) at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar) --- End of inner exception stack trace ---
这是我用来调用 web api 的代码。通过浏览器调用 web api 工作得很好。
static void Main(string[] args)
{
string url = "https://app1/api/AddUrl?longUrl=http://google.com";
var result = GetTinyUrl(url).Result;
Console.WriteLine(result.ShortUrl);
}
protected static async Task<UrlResponse> GetUrl(string baseUrl)
{
HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
var client = new HttpClient(handler);
var response = client.GetAsync(baseUrl).Result;
if (response.IsSuccessStatusCode)
{
HttpResponseMessage response1 = response;
response.EnsureSuccessStatusCode();
var resp = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<UrlResponse>(resp);
return result;
}
return null;
}
最佳答案
只是说我在连接到我正在编写的 azure 服务时花了几个小时来研究类似的问题。
无法弄清楚为什么 postman 工作得很好,但我的代码却惨遭失败。同样,我在代码中尝试的其他 URL 工作正常或出现预期失败。
最后失败的原因是我忘记降低最低 TLS 版本 在 TLS/SSL 设置 刀刃!!
我认为旧版本的 HttpClient 只能处理 TLS v1.0。
关于c# - httpclient.GetAsync : The underlying connection was closed: An unexpected error occurred on a send,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54089849/