问题
I have a class which connects to a Web API, therefore I am initialising a static HTTPClient at top of the class like this
private static readonly HttpClient httpClient = new HttpClient();
https://docs.microsoft.com/enus/azure/architecture/antipatterns/improper-instantiation/
This HTTPClient is used by all public methods within the class to contact the API, each method except login() requires a basic authentication header, this header should be in the format:
Authorization: Basic device_id:X-Secret-Key
Where the device_id is a constant for this instance of the class and the secret key a return from the login() method.
Therefore should every method contain:
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo)));
Where request is the HTTPRequestMessage being created and authInfo is a string in the format device_id:X-Secret-Key.
Or should a every method call a seperate HTTPClient from the one used by the Login() function, declared like:
var handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential (device_id, secret_key);
var client = new HttpClient (handler);
Thank you for any responses
回答1:
The Authorization header, add it to the httpClient:
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo)));
After you add this header ONCE, every future calls to the WEB API service should be authorized.
来源:https://stackoverflow.com/questions/45609530/authentication-handling-using-httpclient