Http Post Request in C# With Authorization Header
I recently worked on an Asp.Net Core project and had to make a couple of HTTP requests to a particular API endpoint due to a whole range of systems that needed to be integrated with each other for some reason.
Most of the code snippets or solutions I have seen especially when making a simple Post Request tend to be scattered with repeating segments especially when it has to do with adding Authorization headers as well as Content-type, along with the data that is to be sent to the URI endpoint.
We’ll be making use of WebRequest, which is an abstract class defined in the System.Net namespace, Newtonsoft which is used to Serialize and deserialize any .NET Core object with Json.NET’s powerful JSON serializer.
Now let’s see how we can write a simple but effective method, for making a Post request in C#.
Ok, let's walk through the above code snippet.
We have a method defined as PostAsync, which takes in three parameters i.e token, URL, and content. Note that this content can be of any object type.
Next, we have the request definitions provided by the WebRequest class, You use the Create method of WebRequest to create an instance of WebRequest.
To actually make the post request we need to assign the request method to a string of “POST”, and notice the request.Headers.Add method, which takes in a name-value pair param. In this case, we are using an Authorization Header which requires an access token. Simple right?
Now Let’s see the part where we make the actual request, which also determines the response we get.
Notice the try-catch statements, the try statement allows you to define a block of code to be tested for errors while it is being executed, while the catch statement allows you to define a block of code to be executed if an error occurs in the try block.
In this case, we are expecting different responses, First is the actual response, which is expected when the request is made, then if anything goes wrong, we get an exception and its response as well.
Finally, the Newtonsoft JSON package is used to deserialize these responses, to an actual object. Note that this varies base on our use cases.
We now see how easy it is to make a post request in c#, adding the content-type, authorization header, and the content itself.
I tried as much as I can to make this readable and concise, so if you have any questions or corrections, I’ll be glad to know.