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 -

1{
2    "firstName": "Andrew",
3    "lastnName": "Adams",
4     "age": 20
5}
 
Use Fiddler to make the request –

The response you get back will look like –

 1{
 2    "args": {},
 3    "data": {
 4        "firstName": "Andrew",
 5        "lastnName": "Adams",
 6        "age": 20
 7    },
 8    "files": {},
 9    "form": {},
10    "headers": {
11        "x-forwarded-proto": "https",
12        "host": "postman-echo.com",
13        "content-length": "77",
14        "authorization": "Basic YWFkYW1zOmtkc2hnczg5ZzJxamF3MDln",
15        "content-type": "application/json",
16        "user-agent": "Fiddler",
17        "x-forwarded-port": "443"
18    },
19    "json": {
20        "firstName": "Andrew",
21        "lastnName": "Adams",
22        "age": 20
23    },
24    "url": "https://postman-echo.com/post"
25}
 
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 –

 1public class PersonRequest
 2{
 3    public PersonRequest(string firstName, string lastName, int age)
 4    {
 5        FirstName = firstName;
 6        LastName = lastName;
 7        Age = age;
 8    }
 9    [JsonPropertyName("firstName")]
10    public string FirstName { get;  }
11
12    [JsonPropertyName("lastnName")]
13    public string LastName { get; }
14
15    [JsonPropertyName("age")]
16    public int Age { get;  }
17}
 
This is the PersonResponse, there are classes to represent the other types (Data, Headers, and Json) you can find them in the source code.

 1public class PersonResponse
 2{
 3    public override string ToString()
 4    {
 5        return $"Response includes \\n \\t {Data.ToString()} \\n \\t Auth header: {Headers.Authorization}";
 6    }
 7
 8    [JsonPropertyName("data")]
 9    public Data Data { get; set; }
10
11    [JsonPropertyName("headers")]
12    public Headers Headers { get; set; }
13
14    [JsonPropertyName("json")]
15    public Data Json { get; set; }
16
17    [JsonPropertyName("url")]
18    public Uri Url { get; set; }
19}

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 -

1public static string Base64Encode(string textToEncode)
2{
3      byte[] textAsBytes = Encoding.UTF8.GetBytes(textToEncode);
4      return Convert.ToBase64String(textAsBytes);
5}

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.

 1HttpClient httpClient = new HttpClient
 2{
 3    BaseAddress = new Uri("https://postman-echo.com/")
 4};
 5
 6httpClient.DefaultRequestHeaders.Add("Authorization", $"Basic {Base64Encode($"{Username}:{Password}")}");
 7//Alternative way to add the authorization header 
 8//httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Base64Encode($"{Username}:{Password}"));
 9
10PersonRequest request = new PersonRequest("Andrew", "Adams", 99);
 
Make the request and deserialize the response as the PersonResponse

1HttpResponseMessage httpResponseMessage = await httpClient.PostAsJsonAsync("/post", request).ConfigureAwait(false);
2PersonResponse personResponse = await httpResponseMessage.Content.ReadAsAsync<PersonResponse>().ConfigureAwait(false);
 
There you go, not that easy if you are new to .NET.

Full source code here.

comments powered by Disqus

Related