C#关于使用验证访问令牌参数的两种写法

218 阅读4分钟

最近对接一个快递公司和一个电子发票api,都是使用验证访问令牌进行请求。写了两个请求参数方法。

第一个使用 client.DefaultRequestHeaders.Authorization

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

再看微软官网解析:

QQ_1732006313891.png

将生成以下标头:

Authorization: Bearer ACCESS_TOKEN

learn.microsoft.com/zh-cn/dotne…

第二个使用 字典Dictionary<string, string>

 var headers = new Dictionary<string, string>();
            headers.Add("Authorization", string.Format("Bearer {0}", accessToken));
 if (headers != null)
 {
     foreach (var header in headers)
     {
         client.DefaultRequestHeaders.Add(header.Key, header.Value);
     }
 }

好奇这两种写法有什么区别,问了豆包ai,然后又自己 实践了一下。对于单个令牌参数,这两种写法完全是一样的。对于多个参数的是使用字典。

看看豆包ai 回答。

1. HttpClient client = new HttpClient(); foreach (var header in headers) client.DefaultRequestHeaders.Add(header.Key, header.Value);

  • 代码功能
    • 首先创建了一个 HttpClient 实例,它是在.NET 中用于发送 HTTP 请求的类。
    • 然后通过一个循环遍历 headers 集合(这里假设 headers 是一个字典类型,如 Dictionary<string, string>,其中键是请求头的名称,值是请求头的值)。
    • 对于每个遍历到的请求头键值对,使用 client.DefaultRequestHeaders.Add 方法将其添加到 HttpClient 的默认请求头集合中。这样,在后续使用这个 HttpClient 实例发送 HTTP 请求时,这些添加的请求头就会被包含在请求中一起发送出去。
  • 常见应用场景
    • 当需要在多个 HTTP 请求中添加一些通用的请求头信息时,就可以采用这种方式。例如,可能需要添加一些自定义的标识头(如用户的唯一标识、应用程序的版本号等),或者一些与服务端约定好的用于身份验证或请求处理的特定头信息(如特定的业务逻辑相关的请求头)。

2. client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

  • 代码功能
    • 这里是在设置 HttpClientAuthorization 请求头的值。Authorization 请求头通常用于在 HTTP 请求中提供身份验证信息。
    • 通过创建一个 AuthenticationHeaderValue 实例,并传入身份验证类型(这里是 "Bearer",表示使用 Bearer 令牌进行身份验证)和具体的 accessToken(访问令牌,通常是在用户登录或获取授权后得到的一个字符串,用于标识用户的授权状态和权限范围),然后将这个实例赋值给 client.DefaultRequestHeaders.Authorization,从而在后续发送的 HTTP 请求中,请求头中会包含正确的身份验证信息,以便服务端能够识别请求者的身份并进行相应的权限验证和处理。
  • 常见应用场景
    • 在需要对 HTTP 请求进行基于令牌的身份验证时使用。比如,在一个 Web API 应用程序中,客户端在成功登录后会获得一个访问令牌,之后在向需要授权访问的 API 端点发送请求时,就需要通过设置 Authorization 请求头来提供这个访问令牌,以证明自己的身份和权限,使得服务端能够允许其访问相应的资源。

总体来说,第一段代码是用于添加各种通用的请求头信息,而第二段代码则是专门针对设置身份验证相关的请求头(具体是 Authorization 请求头),它们在构建完整的 HTTP 请求、满足不同的业务需求(如添加自定义标识、进行身份验证等)方面都起着重要的作用。

模拟请求端代码

   string content = JsonConvert.SerializeObject(model);
            string countryCode="sg";
            string postUrl = string.Format("http://localhost:26400/ApitTest/SGNJTest", countryCode);
            string accessToken = "qzj0cjAtu9NrbmK27ngo5ptmGtaMYYd3";
           var response = HttpHelperService.HttpPost(postUrl, content, "application/json", null, 30000, accessToken); // 对于单个token 两种方法是一样的
            var headers = new Dictionary<string, string>();
            headers.Add("Authorization", string.Format("Bearer {0}", accessToken));
        //   var response = HttpHelperService.HttpPost22(postUrl, content, "application/json", headers, 30000);
            string responseStr = response.Content.ReadAsStringAsync().Result;

接收端代码

[HttpPost]
public ActionResult SGNJTest(dynamic model)
{
    string [] authPa = Request.Headers.AllKeys;
    string accessToken = HttpContext.Request.Headers["Authorization"];

    string Authorization = Request.Headers["Authorization"]; //获取ID

    return Json(new { headerData = Authorization, Data = "999999", accessTokenData = accessToken });
}

请求方法代码

      public static HttpResponseMessage HttpPost(string url, string body = null, string contentType = null, Dictionary<string, string> headers = null, int timeOut = 30, string accessToken = "")
        {
            body = body ?? "";
            SetCertificatePolicy();
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            using (HttpClient client = new HttpClient())
            {
                client.Timeout = new TimeSpan(0, 0, timeOut);
                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                }
                if (!string.IsNullOrEmpty(accessToken))
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                }
                using (HttpContent httpContent = new StringContent(body, Encoding.UTF8))
                {
                    if (contentType != null)
                        httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);

                    HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
                    return response;
                }
            }
        }

        public static HttpResponseMessage HttpPost22(string url, string body = null, string contentType = null, Dictionary<string, string> headers = null, int timeOut = 30)
        {
            body = body ?? "";
            SetCertificatePolicy();
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            using (HttpClient client = new HttpClient())
            {
                client.Timeout = new TimeSpan(0, 0, timeOut);
                if (headers != null)
                {
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
                using (HttpContent httpContent = new StringContent(body, Encoding.UTF8))
                {
                    if (contentType != null)
                        httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);

                    HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
                    return response;
                }
            }
        }

/// <summary>
        /// 设置证书策略
        /// </summary>
        public static void SetCertificatePolicy()
        {
            System.Net.ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;
        }

        /// <summary>
        /// Remotes the certificate validate.
        /// </summary>
        private static bool RemoteCertificateValidate(
           object sender, X509Certificate cert,
            X509Chain chain, SslPolicyErrors error)
        {
            return true;
        }

看百遍不如实践一遍,会有各种收获。