HttpClient.SendAsync HttpException:客户端断开连接
本文关键字:断开 连接 客户端 SendAsync HttpException HttpClient | 更新日期: 2023-09-27 18:14:53
我有一个ASP。. NET web API应用程序托管在Windows Azure web角色中。此应用程序的目的是代理Http请求到其他启用web的端点-如服务总线中继,并返回他们的响应。
有时,我们的应用程序在发送具有较大负载(>5MB)的请求时抛出异常。对于大负载的请求,这可能在20个请求中发生1个。
Exception Details: System。AggregateException:一个或多个错误发生。--> System.Web.HttpException: The client disconnected.
System.Web.Hosting.IIS7WorkerRequest.EndRead (IAsyncResultasyncResult)System.Web.HttpBufferlessInputStream。EndRead (IAsyncResult asyncResult)System.Net.Http.StreamToStreamCopy.BufferReadCallback (IAsyncResult——内部异常堆栈跟踪结束——-->(内部异常#0)System.Web.HttpException (0x800703E3):客户端断开连接。在System.Web.Hosting.IIS7WorkerRequest。EndRead (IAsyncResult asyncResult)System.Web.HttpBufferlessInputStream.EndRead (IAsyncResultasyncResult)System.Net.Http.StreamToStreamCopy.BufferReadCallback (IAsyncResult基于"增大化现实"技术)& lt; -;TraceSource 'w3wp.exe'事件
我们使用。net 4.5中的System.Net.HttpClient发送这些Http请求。
public class ProxyController : ApiController
{
private static readonly HttpClient HttpClient = new HttpClient();
private static readonly Uri BaseUri = new Uri("http://webendpoint.com");
public HttpResponseMessage Post()
{
var newUri = new Uri(BaseUri, Request.RequestUri.PathAndQuery);
var request = new HttpRequestMessage(HttpMethod.Post, newUri)
{
Content = this.Request.Content
};
var task = HttpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
task.Wait();
var response = task.Result;
return new HttpResponseMessage(response.StatusCode)
{
Content = new PushStreamContent((stream, content, ctx) =>
{
var tempStream = response.Content.ReadAsStreamAsync().Result;
tempStream.CopyToAsync(stream).Wait();
stream.Flush();
stream.Close();
})
};
}
}
有什么想法可以导致这个问题吗?
尝试返回Task版本,然后将同步代码替换为async。没有了。"结果"的东西,而不是使用"await"关键字,并把" async "关键字在你的方法。像这样:
public class ProxyController : ApiController
{
private static readonly HttpClient HttpClient = new HttpClient();
private static readonly Uri BaseUri = new Uri("http://webendpoint.com");
public async Task<HttpResponseMessage> Post()
{
var newUri = new Uri(BaseUri, Request.RequestUri.PathAndQuery);
var request = new HttpRequestMessage(HttpMethod.Post, newUri)
{
Content = Request.Content
};
var response = await HttpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
return new HttpResponseMessage(response.StatusCode)
{
Content = new PushStreamContent(async (stream, content, ctx) =>
{
var tempStream = await response.Content.ReadAsStreamAsync();
await tempStream.CopyToAsync(stream);
stream.Flush();
stream.Close();
})
};
}
}