c# – WinHttpException:与服务器的连接异常终止
作者:互联网
我有一个ASP.Net核心Wep API项目,它执行以下任务:
>通过名为ProcessController的控制器接收请求.
>获取传入的请求并将数据格式化为字符串.
>使用以下HttpProcessor类中的PostChargeAsync方法在URL上发布上述格式化消息,并等待响应消息执行进一步处理.
请注意,HttpClient是使用IoC注入的,并且是单例.
public class HttpProcessor
{
private readonly HttpClient _httpClient;
public HttpProcessor(HttpClient httpClient)
{
_httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
}
public async Task<string> PostChargeAsync(string payload)
{
using (var httpRequest = BuildHttpRequest(payload))
{
try
{
using (var httpResponse = await _httpClient.SendAsync(httpRequest).ConfigureAwait(false))
{
httpResponse.EnsureSuccessStatusCode();
using (var httpContent = httpResponse.Content)
{
return await httpContent.ReadAsStringAsync();
}
}
}
catch (HttpRequestException ex)
{
throw;
}
catch (TimeoutException ex)
{
throw;
}
catch (System.Exception ex)
{
throw;
}
}
}
private HttpRequestMessage BuildHttpRequest(string content)
{
return new HttpRequestMessage
{
Content = new StringContent(content, Encoding.UTF8, "application/xml"),
Method = HttpMethod.Post,
RequestUri = new Uri("https://test/process"),
};
}
}
问题是当在ProcessController上发送并行请求(~30-50请求/分钟)并调用PostChargeAsync方法时,我得到以下异常:
System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.Http.WinHttpException: The connection with the server was terminated abnormally
我尝试在Web.Config中添加以下设置以增加connectionManagement中的maxconnection:
<system.net>
<connectionManagement>
<add address="*" maxconnection="100"/>
</connectionManagement>
</system.net>
但我仍然得到上述异常.
什么会引起上述问题?
解决方法:
我们从HttpClient转移到了HttpWebRequest,上面提到的问题已经解决了. HttpClient在.Net Core Runtime 2.0上存在一些问题.请注意,在创建此帖子时,我使用的是.NET Core SDK 2.1.4和.NET Core Runtime 2.0.5.
标签:c,http,dotnet-httpclient,asp-net-core 来源: https://codeday.me/bug/20190705/1389391.html