c# – HttpClient.SendAsync HttpException:客户端已断开连接
我有一个在
Windows Azure Web角色中托管的ASP.NET Web API应用程序.
此应用程序的目的是将Http请求代理到其他启用Web的端点(例如服务总线中继)并返回其响应. 有时,我们的应用程序在发送具有重要(> 5MB)有效负载的请求时会抛出异常.这可能发生在具有大负载的20个请求中的1个.
我们使用.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(); }) }; } } 有什么可能导致这个问题的想法? 解决方法
尝试返回任务版本,然后用异步替换同步代码.不再使用“.Results”内容,而是使用“await”关键字并在方法上添加“asyc”关键字.像这样的东西:
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,newUri) { Content = Request.Content }; var response = await HttpClient.SendAsync(request,HttpCompletionOption.ResponseHeadersRead); return new HttpResponseMessage(response.StatusCode) { Content = new PushStreamContent(async (stream,ctx) => { var tempStream = await response.Content.ReadAsStreamAsync(); await tempStream.CopyToAsync(stream); stream.Flush(); stream.Close(); }) }; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |