Create HttpClient service to reuse

0

How should I create my service HttpClient to be instantiated once in the application to be able to reuse that instance throughout the application and avoid exhausting the sockets ?.

All this given that I am consuming a WebApi.

Currently I have my service like this:

public static HttpClient GenerateClient()
{
    HttpClient client = new HttpClient();

    client.BaseAddress = new Uri("http://0.0.0.0:0000/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(string.IsNullOrEmpty(token);

    return client;
}
    
asked by vcasas 10.05.2018 в 15:20
source

2 answers

0

I am afraid that you are in a confusion, HttpClient will only work to make requests of type HTTP, that is, request / response, unlike the socket that keeps an open communication.

If what you want is to create an HTTP request, this would be a very basic example:

using (var client = new HttpClient())
{
    var result = Client.GetAsync("http://miURL.com").Result;
    Console.WriteLine(result.StatusCode);
}

If you really want to use sockets, I suggest you check the official documentation and here I leave another example how to use them.

Abmos links are in English and correspond to the MSDN.

    
answered by 10.05.2018 в 17:08
0

You can implement a Singleton pattern so that you always use the same instance of your HttpClient

static HttpClient _clientInstance;

public static HttpClient GenerateClient()
{
    if (_clientInstance == null) {
        _clientInstance = new HttpClient();
        _clientInstance.BaseAddress = new Uri("http://0.0.0.0:0000/");
        _clientInstance.DefaultRequestHeaders.Accept.Clear();
        _clientInstance.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        _clientInstance.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(string.IsNullOrEmpty(token);
    }
    return _clientInstance;
}

When you need an HttpClient you will always call your static GenerateClient function.

For more details of the Singleton review this link:

link

    
answered by 11.05.2018 в 20:48