# ASP .NET REST API ## Data Transfer Objects (DTOs) A **DTO** is an object that defines how the data will be sent and recieved over the network (usually as JSON). Without a DTO the JSON response (or reqest) could contain irrilevant, wrong or unformatted data. Moreover, by decoupling the JSON response from the actual data model, it's possible to change the latter without breaking the API. DTOs must be mapped to the internal methods. In `EntityDTO.cs`: ```cs namespace .DTOs { // define the data to be serialized in JSON (differs from model) public class EntityDTO { // only properties to be serialized } } ``` ### DTO mapping with Automapper Required NuGet Packages: - `AutoMapper` - `AutoMapper.Extensions.Microsoft.DependencyInjection` A good way to organize mapping configurations is with *profiles*. In `EntitiesProfile.cs`: ```cs using AutoMapper; using .DTOs; using .Model; namespace .Profiles { public class EntitiesProfile : Profile { public EntitiesProfile() { CreateMap(); // map entity to it's DTO } } } ``` In `StartUp.cs`: ```cs public void ConfigureServices(IServiceCollection services) { // other services // let AutoMapper know in what assemblies are the profiles defined services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); // or create a MapperConfiguration services.AddAutoMapper(cfg => { cfg.CreateMap(); cfg.AddProfile(); }) } ``` ### Controller with DTOs ```cs using .Model; using .Repo; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; namespace .Controllers { [Route("api/endpoint")] [ApiController] public class EntitiesController : ControllerBase // MVC controller w/o view { // service or repo (DAL) injection private readonly IMapper _mapper; // AutoMapper class [HttpGet] // GET api/endpoint public ActionResult SelectAllEntities() { ... return Ok(_mapper.Map(entity)); } } } ``` ## Simple API Controller ```cs [Route("api/endpoint")] [ApiController] public class EntitiesController : ControllerBase { // service or repo (DAL) injection [HttpGet] public ActionResult SelectAll() { ... return Ok(entity); } } ```