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:
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);
}
}
}
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);
}
}
}