HttpClient single instance with different authentication headers

后端 未结 1 417
迷失自我
迷失自我 2020-11-29 17:39

Given that the .net HttpClient has been designed with reuse in mind and is intended to be long lived and memory leaks have been reported in short lived instances. What guide

相关标签:
1条回答
  • 2020-11-29 18:17

    If your headers are usually going to be the same then you can set the DefaultRequestHeaders. But you don't need to use that property to specify headers. As you've determined, that just wouldn't work if you're going to have multiple threads using the same client. Changes to the default headers made on one thread would impact requests sent on other threads.

    Although you can set default headers on the client and apply them to each request, the headers are really properties of the request. So when the headers are specific to a request, you would just add them to the request.

    request.Headers.Authorization = new AuthenticationHeaderValue("bearer", bearerToken);
    

    That means you can't use the simplified methods that don't involve creating an HttpRequest. You'll need to use

    public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request)
    

    documented here.


    Some have found it helpful to use extension methods to isolate the code that updates the headers from the rest of a method.

    Example of GET and POST methods done through an extension method that allow you to manipulate the request header and more of the HttpRequestMessage before it is sent:

    public static Task<HttpResponseMessage> GetAsync
        (this HttpClient httpClient, string uri, Action<HttpRequestMessage> preAction)
    {
        var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, uri);
    
        preAction(httpRequestMessage);
    
        return httpClient.SendAsync(httpRequestMessage);
    }
    
    public static Task<HttpResponseMessage> PostAsJsonAsync<T>
        (this HttpClient httpClient, string uri, T value, Action<HttpRequestMessage> preAction)
    {
        var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, uri)
        {
            Content = new ObjectContent<T>
                (value, new JsonMediaTypeFormatter(), (MediaTypeHeaderValue)null)
        };
        preAction(httpRequestMessage);
    
        return httpClient.SendAsync(httpRequestMessage);
    }
    

    These could then be used like the following:

    var response = await httpClient.GetAsync("token",
        x => x.Headers.Authorization = new AuthenticationHeaderValue("basic", clientSecret));
    
    0 讨论(0)
提交回复
热议问题