I have an application (ASP NET .NET Framework) that is sending HTTP requests(calls) to my API (.net framework web API), Some times I have got errors like this - Only one usage of each socket address(protocol/network address/port) is normally permitted. I have checked netstat and found that HttpClient is opening a connection very much and not closing a connection so each time it opens the connection and when the limit of connection has expired it gives that error.
I saw the error in the dev/test and prod environment. But don't find an error in the local run.
Code example: This is a call to API where mainClient() is a function that is creating httpClient
internal static void DeleteWorkflowDocument(int workflowId, int tableid)
{
HttpResponseMessage responseMessage = mainClient().PostAsync("/api/Workflow/DeleteWorkflowDocument?workflowId=" + workflowId + "&tableid=" + tableid, null).Result;
}
And here is HttpClient function
public static HttpClient mainClient()
{
try
{
HttpClient newMainClient = new HttpClient();
newMainClient.BaseAddress = new Uri(System.Configuration.ConfigurationManager.AppSettings["APIURI"]);
newMainClient.DefaultRequestHeaders.Accept.Clear();
newMainClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
newMainClient.Timeout = TimeSpan.FromMinutes(10);
if (HttpContext.Current.Request.Cookies["token__"] != null)
{
newMainClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + HttpContext.Current.Request.Cookies["token__"].Value.ToString());
}
return newMainClient;
}
catch (Exception ex)
{
return null;
}
}
here as you see only one refresh is adding a huge count of connections and not closing connections
The issue stemmed from HttpClient not being a singleton and being instantiated each time it was called:
using (HttpClient client = mainClient())
{
}