Reputation: 21
I have a question about HttpClient
. I have an ASP.NET MVC 6 project. I need call some REST api for get or post some data.
Then I have next logic. User call a server method ip/index>> server get request and call api ip/api/GetSomething>> server get response and return View for user.
Sample code:
[HttpGet]
public async Task<IActionResult> Index()
{
try
{
using (var h = new HttpClient())
{
h.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); //token i got early
h.DefaultRequestHeaders.Add("Keep-Alive", "true");
h.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
string sQueryKadastr = _uRL + $"/api/GetSomething";
contentSave.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
var response = await h.GetAsync(sQueryKadastr);
//did something with response and return View
}
catch (Exception ex)
{
g_Global.Log.Write4Web(User.GetUserName(), $"Errors: ", ex);
}
return View("Error");
}
My method work good (any post, get, put etc), but I know that after using dispose HttpClient, the socket continues to live. And in the future I would can get SocketException.
How can I avoid this? I cannot use one HttpClient
because requests to the server can go simultaneously from different users and they will probably conflict. I mean server can get request in Index action [HttpGet]
and to Index action [HttpPost]
and both method will set himself header to HttpClient
and URI at same the time.
Or maybe I am doing something wrong? I would be grateful for any help.
Solution for safe thread: Is setting the Authorization header in HttpClient safe?
Upvotes: 0
Views: 60