Setting Authorization Header of HttpClient

前端 未结 21 2187
粉色の甜心
粉色の甜心 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:38

    To set basic authentication with C# HttpClient. The following code is working for me.

       using (var client = new HttpClient())
            {
                var webUrl ="http://localhost/saleapi/api/";
                var uri = "api/sales";
                client.BaseAddress = new Uri(webUrl);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.ConnectionClose = true;
    
                //Set Basic Auth
                var user = "username";
                var password = "password";
                var base64String =Convert.ToBase64String( Encoding.ASCII.GetBytes($"{user}:{password}"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",base64String);
    
                var result = await client.PostAsJsonAsync(uri, model);
                return result;
            }
    

提交回复
热议问题