我有一个外部Web服务以RESTful方式通过HTTP协议工作。它可以接受相当大的JSON文档(从1MB到20-30MB),进行一些转换并返回另一个大JSON文档,其大小等于或不小于接受的JSON文档的大小。
通过Postman进行测试时,效果很好。
我使用ASP.NET Core 2.2,并尝试使用HttpClient
进行相同的请求。我的应用程序接受数据,创建相同的JSON文档,然后将其发送到外部Web服务。
这是我使用的代码:
public async Task<TResponse> MakeRequest<TRequest, TResponse>(TRequest request)
{
if (request == null)
throw new ArgumentNullException(nameof(TRequest));
var content = new StringContent(JsonConvert.SerializeObject(request));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Post, Content = content };
var response = await _httpClient.SendAsync(httpRequestMessage);
if (response.IsSuccessStatusCode)
{
string responseString = await response.Content.ReadAsStringAsync();
var responseObject = JsonConvert.DeserializeObject<TResponse>(responseString);
return (responseObject != null) ? responseObject : throw new InvalidOperationException();
}
throw new InvalidOperationException();
}
当JSON文档的大小较小时,效果很好-适用于4KB文档,适用于20KB文档,适用于200KB文档,但是从大约800KB文档开始,它会抛出System.Net.Http.HttpRequestException
System.IOException
仅显示消息服务器返回了无效或无法识别的响应。。
它在第var response = await _httpClient.SendAsync(httpRequestMessage);
行上失败。
我尝试手动创建HttpClient对象或通过IServiceCollection
注入HttpClient对象-同样的行为。
services.AddHttpClient<IExternalWebServiceProxy, ExternalWebServiceProxy>()
.ConfigureHttpClient(x =>
{
x.MaxResponseContentBufferSize = 1024 * 1000 * 100;
});
有什么想法会导致问题吗?
更新-exception.ToString()消息:
System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.IO.IOException: The server returned an invalid or unrecognized response.
at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithNtConnectionAuthAsync(HttpConnection connection, HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
at XXX.XXX.XXX.Internals.NCANodeProxy.MakeRequest[TRequest,TResponse](TRequest request) in D:\Sources\XXX\XXX\XXX.XXX.Core\Internals\ExternalNodeProxy.cs:line 36
at XXX.XXX.XXX.Services.CryptoService.SignFileDocument(SignFileCommand command) in D:\Sources\XXX\XXX\XXX.XXX.Core\Services\CryptoService.cs:line 134