We are using HttpClient
to access the WebAPI
hosted on another server.
We have a MVC5 application which is getting data form WebAPI
window server 2012 R2 with IIS 8.5
Below is the code which using to get data from 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;
But during the PT test I am getting multiple request in TIME_WAIT
state. Due to this we are getting socket exception.
What are the best practices to use HttpClient?
Is there any setting which can release the socket after the use.
Similar Question is here
1. How do I prevent Socket/Port Exhaustion?
2. Why does HttpClient leave sockets open?
but it did not helped me.
Edit 1 More detail
: InnerException- System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: Only one usage of each socket address (protocol/network address/port) is normally permitted 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) --- End of inner exception stack trace --- at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context) at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar) --- End of inner exception stack trace --- : URL- http://x.x.x.com//api/GetMenu
.Result
and you are probably awaiting the call to this code though you haven't shown it in context. – Crowcoder