Setting Authorization Header of HttpClient

前端 未结 21 2278
粉色の甜心
粉色の甜心 2020-11-22 14:53

I have an HttpClient that I am using for a REST API. However I am having trouble setting up the Authorization header. I need to set the header to the token I received from d

21条回答
  •  佛祖请我去吃肉
    2020-11-22 15:14

    This is how i have done it:

    using (HttpClient httpClient = new HttpClient())
    {
       Dictionary tokenDetails = null;
       var messageDetails = new Message { Id = 4, Message1 = des };
       HttpClient client = new HttpClient();
       client.BaseAddress = new Uri("http://localhost:3774/");
       var login = new Dictionary
           {
               {"grant_type", "password"},
               {"username", "sa@role.com"},
               {"password", "lopzwsx@23"},
           };
       var response = client.PostAsync("Token", new FormUrlEncodedContent(login)).Result;
       if (response.IsSuccessStatusCode)
       {
          tokenDetails = JsonConvert.DeserializeObject>(response.Content.ReadAsStringAsync().Result);
          if (tokenDetails != null && tokenDetails.Any())
          {
             var tokenNo = tokenDetails.FirstOrDefault().Value;
             client.DefaultRequestHeaders.Add("Authorization", "Bearer " + tokenNo);
             client.PostAsJsonAsync("api/menu", messageDetails)
                 .ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
          }
       }
    }
    

    This you-tube video help me out a lot. Please check it out. https://www.youtube.com/watch?v=qCwnU06NV5Q

提交回复
热议问题