In my
previous article, I’ve shown how to integrate Automapper feature to our application. In this article, we will learn how to remove null properties from the response body.
Requirements
I’ve used VS2019 for this example. Let's start!
Open Visual Studio, go to File Menu -> New ->Project.
It will display a new project template from where you’ve to choose ASP.NET Core Web Application and click "Next".
As soon as you click the "Next" button, it will ask to configure the template like below.
Give a Project Name -- whatever you feel is meaningful. Here, I’ve given AutoMapperExample.
Click the "Create" button.
After that, it will show the below screen where we’ve to select API template and click the "Create" button.
The project structure will appear in the Solution Explorer like below.
First, install Automapper related NuGet packages. For that, right-click on the project and choose the "Manage NuGet Packages" option.
It’ll open package manager dialog where you’ve to give specific NuGet package name to install. For this demo, we require two AutoMapper NuGet packages -
Automapper
Search for it an click the "Install" button at the right side of the dialogue box.
AutoMapper.Extensions.Microsoft.DependencyInjection
The second package is AutoMapper.Extensions.Microsoft.DependencyInjection
Click "Install" and ensure all the required packages are installed, by just checking inside Dependencies under Solution Explorer like below.
Next, go to the Controllers folder and create Employeecontroller. For this, right-click on the Controllers folder and choose Add->Controller it will show a dialogue as below.
Choose API Controller
It will ask you to enter controller name; here I have given Employee as my controller name.
Inside the controller, paste the below code snippet.
- using System.Collections.Generic;
- using AutoMapper;
- using AutoMapperExample.Data;
- using Microsoft.AspNetCore.Mvc;
- namespace AutoMapperExample.Controllers {
- [Route("api/[controller]")]
- [ApiController]
- public class EmployeeController: ControllerBase {
- private readonly IMapper _mapper;
- public EmployeeController(IMapper mapper) {
- _mapper = mapper;
- }
- public IEnumerable < EmployeeDto > PostEmployee(IEnumerable < EmployeeDto > employeeDtos) {
- Employee employee = new Employee();
-
- var employees = _mapper.Map < IEnumerable < EmployeeDto > ,
- IEnumerable < Employee >> (employeeDtos);
- var empList = employee.GetEmployees(employees);
- var list = _mapper.Map < IEnumerable < Employee > ,
- IEnumerable < EmployeeDto >> (empList);
- return list;
- }
- }
- }
Inside controller, I’ve added the EmployeeDto.cs file with the following code.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- namespace AutoMapperExample.Controllers {
- public class EmployeeDto {
- public int Id {
- get;
- set;
- }
- public string Name {
- get;
- set;
- }
- public string Gender {
- get;
- set;
- }
- public string Mobile {
- get;
- set;
- }
- public string Address {
- get;
- set;
- }
- public string Designation {
- get;
- set;
- }
- }
- }
Now, create a Data folder under Solution Explorer and keep the Employee.cs file in it.
- using AutoMapperExample.Controllers;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- namespace AutoMapperExample.Data {
- public class Employee {
- public int Id {
- get;
- set;
- }
- public string Name {
- get;
- set;
- }
- public string Gender {
- get;
- set;
- }
- public string Mobile {
- get;
- set;
- }
- public string Address {
- get;
- set;
- }
- public string Designation {
- get;
- set;
- }
- public IEnumerable < Employee > GetEmployees(IEnumerable < Employee > employees) {
- return employees;
- }
- }
- }
The above two files will appear in Solution Explorer like below.
If you observe EmployeeController, I’ve injected IMapper on constructor level and along with that, there is PostEmployee method which is responsible to get data from the user and map it to the data layer. In our case, it is Employee.cs file under Data folder. For understanding purposes, I didn’t connect to any database and am just returning whatever the user is sending. What we do here is we just map it from Dto to Data and vice versa.
We are receiving user sent data with the help of EmployeeDto.cs file and mapping that to the Employee.cs file.
In order to map data between these files, we need to add MappingProfile.cs to our project and keep the below code snippet inside it.
- using AutoMapper;
- using AutoMapperExample.Controllers;
- using AutoMapperExample.Data;
- namespace AutoMapperExample {
- public class MappingProfile: Profile {
- public MappingProfile() {
- CreateMap < EmployeeDto, Employee > ();
- CreateMap < Employee, EmployeeDto > ();
- }
- }
- }
After that, we need to configure this file at ConfigureServices() method under Startup.cs file like below.
- public void ConfigureServices(IServiceCollection services) {
-
- var mappingConfig = new MapperConfiguration(mc => {
- mc.AddProfile(new MappingProfile());
- });
- IMapper mapper = mappingConfig.CreateMapper();
- services.AddSingleton(mapper);
- services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
- }
Now, run the application and try to post data into Employee controller PostEmployee method.
In order to send the data, I’m using Postman.
We can see that whatever we send to the controller, it is returning as expected. So far, it is good.
Let us see the actual problem now. What if I send null property to this model?
Let me make the mobile property null and see the response.
If you observe here, the null property is returning in response. So, the solution to avoid null properties in response is add a piece of code inside ConfigureServices method of Startup.cs file like below.
- .AddJsonOptions(options => options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore);
Now, your complete configureServices() method looks like below.
- public void ConfigureServices(IServiceCollection services) {
-
- var mappingConfig = new MapperConfiguration(mc => {
- mc.AddProfile(new MappingProfile());
- });
- IMapper mapper = mappingConfig.CreateMapper();
- services.AddSingleton(mapper);
- services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddJsonOptions(options => options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore);
- }
Now, send the same payload through Postman and see results. This time, you won’t see null property in response. In our case, the mobile property won’t appear this time.
Even though we send null value from the request body, it won’t appear in response result. This is how we can avoid null properties from the response with the help of Jsonserializersettings.
Hope you like this. Keep coding…….