Today I started using HttpClient with basic authentication so I could consume some Web API services (receiving and POSTing data). the first problem I found after reading the Microsoft documentation was that there was no indication on how to use it if you had to authenticate yourself against the API prior to start receiving some data (I’m assuming most APIs out there would require authentication, right?).

After browsing for a while in Stack Oveflow and trying different approaches I found that you can pass your credentials (ASCII encoded) inside the DefaultRequestHeaders.Authorization header value.

The following is an example of a unit test created to test the PostJsonAsync action (the message body of the request is a serialized Json object but you could pass a well formed json string as well)

If instead, you would like to pass a query string check out this blog: How to call HttpClient.PostAsync with a query string


Thanks for reading