使用HTTPClient的身份验证处理

编程入门 行业动态 更新时间:2024-10-23 04:47:02
本文介绍了使用HTTPClient的身份验证处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个连接到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的身份验证处理

本文发布于:2023-11-03 16:21:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555563.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:身份验证   HTTPClient

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!