Pass An Object To HttpClient.PostAsync and Serialize As a JSON Body


In my application, I need to utilize a third-party API. For that purpose, I'm using System.Net.Http. I've found several examples on the internet, and I've managed to write code to make a POST request. 

Now, I want to pass an object as a parameter to the HttpClient's POST request. In this post, we will discuss how to pass an object to HttpClient.PostAsync and serialize it as a JSON body.

Let's take a look on passing an object to HttpClient.PostAsync and serializing it as a JSON body in C#, let's consider an Employee object with properties like Id, FirstName, LastName, Salary, and Department:

  1. First, ensure that we have the necessary using directives at the top of our file:
  2.             using System;
                using System.Net.Http;
                using System.Text.Json;
                using System.Threading.Tasks;
            
  3. Next, we'll define our Employee class:
  4.             public class Employee
                {
                    public int Id { get; set; }
                    public string FirstName { get; set; }
                    public string LastName { get; set; }
                    public decimal Salary { get; set; }
                    public string Department { get; set; }
                }
            
  5. Then, we'll create an instance of HttpClient to make the HTTP request:
  6.             HttpClient httpClient = new HttpClient();
            
  7. Now, we'll create an instance of our Employee object and populate it with data:
  8.             Employee employee = new Employee
                {
                    Id = 1,
                    FirstName = "John",
                    LastName = "Doe",
                    Salary = 50000.00m,
                    Department = "IT"
                };
            
  9. Next, we'll serialize our Employee object into JSON using System.Text.Json:
  10.             string json = JsonSerializer.Serialize(employee);
            
  11. Finally, we'll send the serialized JSON as the request body using HttpClient.PostAsync:
  12.             HttpResponseMessage response = await httpClient.PostAsync("https://quickpickdeal.com/api/employees", new StringContent(json, Encoding.UTF8, "application/json"));
            
  13. Now let's Handle the response accordingly, such as checking for success or handling errors:
  14.             if (response.IsSuccessStatusCode)
                {
                    // Request was successful
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("Response: " + responseBody);
                }
                else
                {
                    // Request failed
                    Console.WriteLine("Error: " + response.StatusCode);
                }
            

Here's the complete code for passing an Employee object to HttpClient.PostAsync and serializing it as a JSON body in C#:

        using System;
        using System.Net.Http;
        using System.Text;
        using System.Text.Json;
        using System.Threading.Tasks;

        public class Employee
        {
            public int Id { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public decimal Salary { get; set; }
            public string Department { get; set; }
        }

        class Program
        {
            static async Task Main(string[] args)
            {
                // Create HttpClient instance
                HttpClient httpClient = new HttpClient();

                // Create Employee object and populate it with data
                Employee employee = new Employee
                {
                    Id = 1,
                    FirstName = "John",
                    LastName = "Doe",
                    Salary = 50000.00m,
                    Department = "IT"
                };

                // Serialize Employee object into JSON
                string json = JsonSerializer.Serialize(employee);

                try
                {
                    // Send JSON as request body using HttpClient.PostAsync
                    HttpResponseMessage response = await httpClient.PostAsync("https://quickpickdeal.com/api/employees", new StringContent(json, Encoding.UTF8, "application/json"));

                    
                    if (response.IsSuccessStatusCode)
                    {
                        // Request was successful
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine("Response: " + responseBody);
                    }
                    else
                    {
                      
                        Console.WriteLine("Error: " + response.StatusCode);
                    }
                }
                catch (Exception ex)
                {
                    
                    Console.WriteLine("Exception: " + ex.Message);
                }
            }
        }
    
2

We can also use PostAsJsonAsync, which simplifies the process of sending JSON data with HttpClient in C#:

        using System;
        using System.Net.Http;
        using System.Threading.Tasks;

        public class Employee
        {
            public int Id { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public decimal Salary { get; set; }
            public string Department { get; set; }
        }

        class Program
        {
            static async Task Main(string[] args)
            {
                // Create HttpClient instance
                HttpClient httpClient = new HttpClient();

                // Create Employee object and populate it with data
                Employee employee = new Employee
                {
                    Id = 1,
                    FirstName = "John",
                    LastName = "Doe",
                    Salary = 50000.00m,
                    Department = "IT"
                };

                try
                {
                    // Send Employee object as JSON using PostAsJsonAsync
                    HttpResponseMessage response = await httpClient.PostAsJsonAsync("https://quickpickdeal.com/api/employees", employee);

                    
                    if (response.IsSuccessStatusCode)
                    {
                        // Request was successful
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine("Response: " + responseBody);
                    }
                    else
                    {
                     
                        Console.WriteLine("Error: " + response.StatusCode);
                    }
                }
                catch (Exception ex)
                {
                    
                    Console.WriteLine("Exception: " + ex.Message);
                }
            }
        }
    


  • We have created an instance of HttpClient, which allows us to send HTTP requests and receive responses from a specified URI and after that create an instance of the Employee class and populate it with sample data such as Id, FirstName, LastName, Salary, and Department.
  • We make use of the PostAsJsonAsync method of the httpClient instance to send the employee object as JSON to a specified URL, which in this case is "https://quickpickdeal.com/api/employees" , this function sends an HTTP POST request asynchronously and automatically serializes the provided object into JSON format to be included in the request body.
  • After successful call, we read the response from the server in the HttpResponseMessage object named response.If the response indicates success and then read the response content as a string asynchronously using response.Content.ReadAsStringAsync().

3

If you also wants to include the toekn in header then you can use below examples of using both PostAsJsonAsync and PostAsync with HttpClient in C#, along with adding a bearer token for authorization:

        using System;
        using System.Net.Http;
        using System.Net.Http.Headers;
        using System.Text.Json;
        using System.Threading.Tasks;

        public class Employee
        {
            public int Id { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public decimal Salary { get; set; }
            public string Department { get; set; }
        }

        class Program
        {
            static async Task Main(string[] args)
            {
                string apiUrl = "https://quickpickdeal.com/api/employees";
string bearerToken = "sjhdsjdb9393hdbjddb"; // Create HttpClient instance HttpClient httpClient = new HttpClient(); // Add bearer token for authorization httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken); // Create Employee object and populate it with data Employee employee = new Employee { Id = 1, FirstName = "John", LastName = "Doe", Salary = 50000.00m, Department = "IT" }; try { // Using PostAsJsonAsync HttpResponseMessage responseJson = await httpClient.PostAsJsonAsync(apiUrl, employee); if (responseJson.IsSuccessStatusCode) { string responseBody = await responseJson.Content.ReadAsStringAsync(); Console.WriteLine("Response using PostAsJsonAsync: " + responseBody); } else { Console.WriteLine("Error using PostAsJsonAsync: " + responseJson.StatusCode); } // Using PostAsync with JSON content string json = JsonSerializer.Serialize(employee); var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json"); HttpResponseMessage responsePost = await httpClient.PostAsync(apiUrl, content); if (responsePost.IsSuccessStatusCode) { string responseBody = await responsePost.Content.ReadAsStringAsync(); Console.WriteLine("Response using PostAsync with JSON content: " + responseBody); } else { Console.WriteLine("Error using PostAsync with JSON content: " + responsePost.StatusCode); } } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); } } }