POST with HttpClient and Basic Authorization
Full source code here.
A non .NET developer friend asked me to help him write a sample C# application that exercises a POST
endpoint he wrote, it requires Basic authorization. After a quick search, I found that there are relatively few good examples of doing this in .NET.
Step 1 - Authorization
The Basic authorization header that is added to the request, is in the shape Authorization: Basic {authorization string}
.
The {authorization string} is usually in the form of {username:password}, but it has to be base64 encoded. Go to https://www.base64encode.org/ and paste in something like -
aadams:kdshgs89g2qjaw09g
and you will get back
YWFkYW1zOmtkc2hnczg5ZzJxamF3MDln
That is your authorization string.
Step 2 – Getting the Json
I like using Fiddler, but you can use Postman, Insomnia, or anything else you find too. Be careful with curl and Postman though, you don’t need to encode the authorization header with them, but you do with the likes of Fiddler and you must do it in the C# code.
For this walkthrough, I am going to use this handy echoing endpoint https://postman-echo.com/post. You send it a request, it responds with the request you sent, request header details, and other useful information.
When making a request to real API you will get the shape of the Json from the documentation for that API (and probably the response), but let’s pretend the documentation doesn’t include the response, or as often happens it is out of date.
Let’s say this is the Json to send -
|
|
Use Fiddler to make the request –
The response you get back will look like –
|
|
Great, you have the request and response. Let’s start on the C#.
Step 3 – Convert Json to C#
This is easy thanks to tools like http://json2csharp.com/ and https://app.quicktype.io/.
Simply paste in the Json and it will produce the C# class or classes to represent the Json.
Depending on the Json serializer you are planning to use, you might need to make some adjustments to the C# produced, for example, if you want to use System.Text.Json
you will need to change the attribute names from JsonProperty
to JsonPropertyName
.
Here is the PersonRequest
class –
|
|
This is the
PersonResponse
, there are classes to represent the other types (Data, Headers, and Json) you can find them in the source code.
|
|
Step 4 – Encoding the Authorization String
This is a simple way to encode the string, but you could create an extension method to do the same -
|
|
Step 5 – Making the request, finally!
Add the Microsoft.AspNet.WebApi.Client
nuget package to the project.
Now that all the plumbing is in place, it’s time to get the HttpClient
to send the request.
|
|
Make the request and deserialize the response as the
PersonResponse
–
|
|
There you go, not that easy if you are new to .NET.
Full source code here.