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:
- First, ensure that we have the necessary using directives at the top of our file:
- Next, we'll define our Employee class:
- Then, we'll create an instance of HttpClient to make the HTTP request:
- Now, we'll create an instance of our Employee object and populate it with data:
- Next, we'll serialize our Employee object into JSON using System.Text.Json:
- Finally, we'll send the serialized JSON as the request body using HttpClient.PostAsync:
- Now let's Handle the response accordingly, such as checking for success or handling errors:
using System; using System.Net.Http; 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; } }
HttpClient httpClient = new HttpClient();
Employee employee = new Employee { Id = 1, FirstName = "John", LastName = "Doe", Salary = 50000.00m, Department = "IT" };
string json = JsonSerializer.Serialize(employee);
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 { // 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); } } }
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().
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); } } }
Read Similar Articles
- [Simple Way]-Add/Delete Table Rows Dynamically Using JavaScript
- [Fixed] "No job functions found" Try making your job classes and methods public in AzureFunctions
- Hot To Get The Exact Time For A Remote Server C#
- Water Heater Power Consumption Calculator | How Much Electricity An Electric Water Heater Use
- Download Free Sample Xml File With Multiple Records
- Solved Error : 400 bad request error: "A non-empty request body is required"
- Crud operation in Asp .Net Core using Razor Pages Step by Step
- Solution : cannot resolve reference to bean 'cassandratemplate' while setting bean property 'cassandratemplate