【发布时间】:2018-01-23 06:25:36
【问题描述】:
我有一个 ASP.Net Core 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 中的最大连接数:
<system.net>
<connectionManagement>
<add address="*" maxconnection="100"/>
</connectionManagement>
</system.net>
但我仍然遇到上述异常。
有什么想法会导致上述问题吗?
【问题讨论】:
-
您能否澄清一下:您发布的代码:即 PostChargeAsync 处理请求?如果是这样,您的错误表明与哪个服务器终止?
-
@DaniDev ProcessController 正在处理请求。请求被格式化,然后使用 PostChargeAsync 方法使用 uri "test/process" 将格式化的请求发布到另一个第三方系统。我没有包含真正的 URI。
-
您是否检查过防火墙或杀毒软件是否阻止连接?
-
异常不是连续的而是间歇性的。
-
@nasiroudin 我认为您尝试通过配置解决此问题是正确的。只是想确定它应该是App、IIS还是Server?这就是为什么我试图了解您的错误的来源(和含义)。你能澄清这个错误发生在哪里(在你的代码中?)以及有问题的服务器吗?
标签: c# http asp.net-core dotnet-httpclient