调用HttpClient.PostAsync时传token等值

2023-10-31 11:32:54 浏览数 (1)

做内部接口转发时加token验证需要传token值过去,有如下两种方式:

代码语言:c#复制
 string jsonContent = JsonConvert.SerializeObject(args);
 using(var clientUrl = new HttpClient())
 {
     var token = "token的值";
     // 法①
     clientUrl.DefaultRequestHeaders.Add("token", token);
     var data = new StringContent(jsonContent, Encoding.UTF8, "application/json");
     result = clientUrl.PostAsync(url, data).Result.Content.ReadAsStringAsync().Result;
   
     // 法②
     var data = new StringContent(jsonContent, Encoding.UTF8, "application/json");
     data.Headers.Add("token", token);
     result = clientUrl.PostAsync(url, data).Result.Content.ReadAsStringAsync().Result;
 }

遇到此问题做此记录,如有帮助,欢迎点赞关注收藏!

0 人点赞