Since Microsoft recommends that the HttpClient be created once and reused throughout the life of a program, I wondering how to update DefaultRequestHeaders when for example, the token has expired and need to be refresh.
DefaultRequestHeaders is more over not thread safe (for what I know) and the list of headers defined there, shared by all potentially pending requests. Clear() the list and Add() the header with a new token, seems not the wise thing to do.
Update
To be more precise, I don't want/need to change request headers for every request. Only when I've got a HTTP 401 status code.
Wire up a message handler with your HttpClient when you register the IHttpClient in the DI container registry phase or use another pattern such as a factory or singleton to return an instance of the IHttpClient with a custom message handler. Inspect the outbound call and add the necessary headers.
https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/httpclient-message-handlers
Sample header message handler
Sample logger message handler:
}
Add it to the pipeline
Threading Concerns
Regarding threading concerns or concurrency, the
HttpRequestMessageparameter on theSendAsyncmethod will be per request. If you add the header to therequest.Headerscollection, you will updating headers for that instance of the request only (i.e., not globally )Or use the Authorization property on the
request.Headersinstance:Please see MSDN link below
https://msdn.microsoft.com/en-us/library/system.net.http.httprequestmessage
If you use
DefaultRequestHeaderson a static, shared, singleton, Lifestyle.Singleton, etc, instance of the HttpClient then you will have threading concerns and need proper synchronization to update theDefaultRequestHeaderscollection.