我有一个连接到Web API的类,因此我正在像这样的类顶部初始化一个静态HTTPClient
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();docs.microsoft/enus/天蓝色/体系结构/反模式/不正确的示例/
该类中的所有公共方法都使用此HTTPClient来联系API,除login()之外的每个方法都需要一个基本的身份验证标头,该标头应采用以下格式:
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:
授权:基本device_id:X-密钥-
Authorization: Basic device_id:X-Secret-Key
其中device_id是该类实例的常量,而秘密密钥是login()方法的返回.
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)));其中request是正在创建的HTTPRequestMessage,而authInfo是格式为device_id:X-Secret-Key的字符串.
Where request is the HTTPRequestMessage being created and authInfo is a string in the format device_id:X-Secret-Key.
或者,每个方法都应从Login()函数使用的方法中调用一个单独的HTTPClient,声明如下:
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);谢谢您的回复
推荐答案Authorization标头,将其添加到httpClient:
The Authorization header, add it to the httpClient:
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo)));添加此标头一次后,应授权以后对WEB API服务的每次调用.
After you add this header ONCE, every future calls to the WEB API service should be authorized.
更多推荐
使用HTTPClient的身份验证处理
发布评论