设置HttpClient的授权标头

问题描述 投票:6回答:1

我有以下代码,我想将post请求的授权设置为:

Authorization:key=somevalue

using (HttpClient client = new HttpClient())
{
     using (StringContent jsonContent = new StringContent(json))
     {
         jsonContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

         using (HttpResponseMessage response = await client.PostAsync("https://android.googleapis.com/gcm/send", jsonContent))
         {
            var reponseString = await response.Content.ReadAsStringAsync();
         }
     }
}

这该怎么做?我真的很挣扎以及以下声明

client.DefaultRequestHeaders.Add("Authorization", "key=" + apiKey);

抛出以下异常

System.Net.Http.dll中出现“System.FormatException”类型的异常,但未在用户代码中处理

c# authorization httpclient httpcontent
1个回答
18
投票

我通过以下代码解决了这个问题。

client.DefaultRequestHeaders.Authorization =
       new AuthenticationHeaderValue("key", "=" + apiKey);
© www.soinside.com 2019 - 2024. All rights reserved.