12. Building a .NET Minimal API with AutoMapper
Introduction In this tutorial, I will walk you through creating a .NET minimal API that leverages AutoMapper for object-to-object mapping. We'll build an API endpoint for creating and returning coupon data.
Step 1: Setting Up the Project First, create a new .NET minimal API project and add the necessary AutoMapper packages:
dotnet add package AutoMapper --version 11.0.1
dotnet add package AutoMapper.Extensions.Microsoft.DependencyInjection --version 11.0.0
Step 2: Creating Models and DTOs Create the models and DTOs in your project.
Models/Coupon.cs:
namespace MagicVilla_CouponAPI.Models
{
public class Coupon
{
public int Id { get; set; }
public string Code { get; set; }
public decimal Discount { get; set; }
public DateTime ExpiryDate { get; set; }
}
}
DTOs/CouponCreateDTO.cs:
namespace MagicVilla_CouponAPI.DTOs
{
public class CouponCreateDTO
{
public string Code { get; set; }
public decimal Discount { get; set; }
public DateTime ExpiryDate { get; set; }
}
}
DTOs/CouponDTO.cs:
namespace MagicVilla_CouponAPI.DTOs
{
public class CouponDTO
{
public int Id { get; set; }
public string Code { get; set; }
public decimal Discount { get; set; }
public DateTime ExpiryDate { get; set; }
}
}
Step 3: Configuring AutoMapper Create a mapping configuration class to define the mappings.
MappingConfig.cs:
using AutoMapper;
using MagicVilla_CouponAPI.DTOs;
using MagicVilla_CouponAPI.Models;
namespace MagicVilla_CouponAPI
{
public class MappingConfig : Profile
{
public MappingConfig()
{
CreateMap<Coupon, CouponCreateDTO>().ReverseMap();
CreateMap<Coupon, CouponDTO>().ReverseMap();
}
}
}
Step 4: Configuring the API Configure AutoMapper and define the API endpoint in Program.cs.
Program.cs:
using AutoMapper;
using MagicVilla_CouponAPI;
using MagicVilla_CouponAPI.DTOs;
using MagicVilla_CouponAPI.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddAutoMapper(typeof(MappingConfig));
var app = builder.Build();
// Configure the HTTP request pipeline.
app.MapPost("/api/coupon", (IMapper _mapper, CouponCreateDTO couponCreateDTO) =>
{
Coupon coupon = _mapper.Map<Coupon>(couponCreateDTO);
CouponDTO couponDTO = _mapper.Map<CouponDTO>(coupon);
return Results.Ok(couponDTO);
});
app.Run();
ย