我们正在使用 HttpClient
访问托管在另一台服务器上的 WebAPI
。
我们有一个MVC5应用程序,从运行IIS 8.5的Window Server 2012 R2获取来自WebAPI
的数据。
以下是用于从webapi获取数据的代码:
//creating static instance of http client
private static HttpClient client = new HttpClient();
//static method to add common header
static ApiCall()
{
client.DefaultRequestHeaders.Add("Authorization",
string.Format("Value {0}", AppSettings.ApiSecurityKey));
client.DefaultRequestHeaders.ConnectionClose = true;
}
//finally posting data to the api
//objprop contains the data and other setting
string url = "apiurl";
var postContent = new StringContent(objprop.DataForPost,
System.Text.Encoding.UTF8, objprop.ContentType);
response = client.PostAsync(url, postContent).Result;
但是在PT测试期间,我得到了多个处于TIME_WAIT
状态的请求。由于这个原因,我们得到了套接字异常。
使用HttpClient的最佳实践是什么?
是否有任何设置可以在使用后释放套接字?
类似的问题在这里
1. 如何防止套接字/端口耗尽?
2. 为什么HttpClient会保持套接字开启?
但是它没有帮助我。
编辑1 更多细节
: InnerException- System.Net.Http.HttpRequestException: 发送请求时发生错误。---> System.Net.WebException:无法连接到远程服务器---> System.Net.Sockets.SocketException:协议/网络地址/端口只允许每个套接字地址 (protocol/network address/port) 通常是被允许 x.x.x:80 at System.Net.Sockets.Socket.InternalEndConnect(IAsyncResult asyncResult) at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception) --- 内部异常堆栈跟踪的结尾 --- at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context) at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar) --- 内部异常堆栈跟踪的结尾 --- : URL- http://x.x.x.com//api/GetMenu
.Result
阻塞异步代码的事实,而且你可能正在等待这段代码的调用,尽管你没有在上下文中展示它。 - Crowcoder