Quantcast
Viewing latest article 12
Browse Latest Browse All 132

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 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 the purpose of this walkthrough I 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 –

{
    "firstName": "Andrew",
    "lastnName": "Adams",
     "age": 20
}

Use Fiddler to make the request –

Image may be NSFW.
Clik here to view.

The response you get back will look like –

{
    "args": {},
    "data": {
        "firstName": "Andrew",
        "lastnName": "Adams",
        "age": 20
    },
    "files": {},
    "form": {},
    "headers": {
        "x-forwarded-proto": "https",
        "host": "postman-echo.com",
        "content-length": "77",
        "authorization": "Basic YWFkYW1zOmtkc2hnczg5ZzJxamF3MDln",
        "content-type": "application/json",
        "user-agent": "Fiddler",
        "x-forwarded-port": "443"
    },
    "json": {
        "firstName": "Andrew",
        "lastnName": "Adams",
        "age": 20
    },
    "url": "https://postman-echo.com/post"
}

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 –

public class PersonRequest
{
	public PersonRequest(string firstName, string lastName, int age)
	{
		FirstName = firstName;
		LastName = lastName;
		Age = age;
	}
	[JsonPropertyName("firstName")]
	public string FirstName { get;  }

	[JsonPropertyName("lastnName")]
	public string LastName { get; }

	[JsonPropertyName("age")]
	public int Age { get;  }
}

This is the PersonResponse, there are classes to represent the other types (Data, Headers and Json) you can find them in the source code.

public class PersonResponse
{
	public override string ToString()
	{
		return $"Response includes \n \t {Data.ToString()} \n \t Auth header: {Headers.Authorization}";
	}

	[JsonPropertyName("data")]
	public Data Data { get; set; }

	[JsonPropertyName("headers")]
	public Headers Headers { get; set; }

	[JsonPropertyName("json")]
	public Data Json { get; set; }

	[JsonPropertyName("url")]
	public Uri Url { get; set; }
}

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 –

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

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.

HttpClient httpClient = new HttpClient
{
	BaseAddress = new Uri("https://postman-echo.com/")
};

httpClient.DefaultRequestHeaders.Add($"Authorization", $"Basic {Base64Encode($"{Username}:{Password}")}");

PersonRequest request = new PersonRequest("Andrew", "Adams", 99);

Make the request and deserialize the response as the PersonResponse

HttpResponseMessage httpResponseMessage = await httpClient.PostAsJsonAsync("/post", request).ConfigureAwait(false);
PersonResponse personResponse = await httpResponseMessage.Content.ReadAsAsync<PersonResponse>().ConfigureAwait(false);

There you go, not that easy if you are new to .NET.

Full source code here.


Viewing latest article 12
Browse Latest Browse All 132

Trending Articles