简体   繁体   中英

HttpClient initialization within a static class

I'm learning C#. Would it be correct to initilize an HttpClient within a static class like this?

public static class Network {
    static string token = "";
    static string baseAddress = "";

    static readonly HttpClient httpClient = new HttpClient();

    static Network() {
        httpClient.BaseAddress = new Uri(Network.baseAddress);
        httpClient.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("Bearer", Network.token);
    }
}

Also is it possible to do the initilization in one line, something like

static readonly HttpClient httpClient = new HttpClient() {
    BaseAddress = new Uri(Network.baseAddress),
    DefaultRequestHeaders.Authorization =
        new AuthenticationHeaderValue("Bearer", Network.token)  //this does not work
};

Yes you can achieve that by doing this:

static readonly HttpClient httpClient = new HttpClient
{
    BaseAddress = new Uri(Network.baseAddress),
    DefaultRequestHeaders =
    {
        Authorization =
            new AuthenticationHeaderValue("Bearer", Network.token)
    }
};

Regarding HttpClient as a singleton, it's in general not the best practice(not optimal control of connection lieftime) but it all depends on how you are going to use it. It wouldn't be sensible to keep HttpClient in memory forever if your application will not use it very often. The best practice is to use named or typed HttpClient or to use IHttpClientFactory . Very descriptive info you can find here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM