Setting Authorization Header of HttpClient

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

    As it is a good practice to reuse the HttpClient instance, for performance and port exhaustion problems, and because none of the answers give this solution (and even leading you toward bad practices :( ), I put here a link towards the answer I made on a similar question :

    https://stackoverflow.com/a/40707446/717372

    Some sources on how to use HttpClient the right way:

    • https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
    • https://blogs.msdn.microsoft.com/alazarev/2017/12/29/disposable-finalizers-and-httpclient/
    0 讨论(0)
  • 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;
            }
    
    0 讨论(0)
  • 2020-11-22 15:38

    Oauth Process flow is complex and there is always a room for one error or another. My suggestion will be to always use the boilerplate code and a set of libraries for OAuth authentication flow.It will make your life easier.

    Here is the link for the set of libraries.OAuth Libraries for .Net

    0 讨论(0)
提交回复
热议问题