C# ASPNET

Entity


public class Animal
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public int Age { get; set; }
} 

dto


public record AnimalCreateDto(string Name, int Age);
public record AnimalUpdateDto(string Name, int Age);

Service Layer (In-memory CRUD)

interface


public interface IAnimalService
{
    IEnumerable<Animal> GetAll();
    Animal? Get(int id);
    Animal Create(AnimalCreateDto dto);
    Animal? Update(int id, AnimalUpdateDto dto);
    bool Delete(int id);
}

async interface


public interface IAnimalService
{
    Task<IEnumerable<Animal>> GetAllAsync();
    Task<Animal?> GetAsync(int id);
    Task<Animal> CreateAsync(AnimalCreateDto dto);
    Task<Animal?> UpdateAsync(int id, AnimalUpdateDto dto);
    Task<bool> DeleteAsync(int id);
}

implementation


      public class AnimalService : IAnimalService
{
    private readonly List _animals = new()
    {
        new Animal { Id = 1, Name = "Chat", Age = 2 },
        new Animal { Id = 2, Name = "Chien", Age = 4 }
    };

    public IEnumerable GetAll() => _animals;

    public Animal? Get(int id) =>
        _animals.FirstOrDefault(a => a.Id == id);

    public Animal Create(AnimalCreateDto dto)
    {
        var newAnimal = new Animal
        {
            Id = _animals.Any() ? _animals.Max(a => a.Id) + 1 : 1,
            Name = dto.Name,
            Age = dto.Age
        };

        _animals.Add(newAnimal);
        return newAnimal;
    }

    public Animal? Update(int id, AnimalUpdateDto dto)
    {
        var a = Get(id);
        if (a == null) return null;

        a.Name = dto.Name;
        a.Age = dto.Age;

        return a;
    }

    public bool Delete(int id)
    {
        var a = Get(id);
        if (a == null) return false;

        _animals.Remove(a);
        return true;
    }
}

async implementation


      public class AnimalService : IAnimalService
{
    private readonly List<Animal> _animals = new()
    {
        new Animal { Id = 1, Name = "Chat", Age = 2 },
        new Animal { Id = 2, Name = "Chien", Age = 4 }
    };

    public Task<IEnumerable<Animal>> GetAllAsync()
        => Task.FromResult(_animals.AsEnumerable());

    public Task<Animal?> GetAsync(int id)
        => Task.FromResult(_animals.FirstOrDefault(a => a.Id == id));

    public Task<Animal> CreateAsync(AnimalCreateDto dto)
    {
        var newAnimal = new Animal
        {
            Id = _animals.Any() ? _animals.Max(a => a.Id) + 1 : 1,
            Name = dto.Name,
            Age = dto.Age
        };

        _animals.Add(newAnimal);
        return Task.FromResult(newAnimal);
    }

    public Task<Animal?> UpdateAsync(int id, AnimalUpdateDto dto)
    {
        var a = _animals.FirstOrDefault(x => x.Id == id);
        if (a == null) return Task.FromResult<Animal?>(null);

        a.Name = dto.Name;
        a.Age = dto.Age;

        return Task.FromResult<Animal?>(a);
    }

    public Task<bool> DeleteAsync(int id)
    {
        var a = _animals.FirstOrDefault(x => x.Id == id);
        if (a == null) return Task.FromResult(false);

        _animals.Remove(a);
        return Task.FromResult(true);
    }
}

program.cs


builder.Services.AddSingleton<IAnimalService, AnimalService>();

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSingleton<IAnimalService, AnimalService>();

Controller


using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class AnimalsController : ControllerBase
{
    private readonly IAnimalService _service;

    public AnimalsController(IAnimalService service)
    {
        _service = service;
    }

    // GET: api/animals
    [HttpGet]
    public IActionResult GetAll()
    {
        return Ok(_service.GetAll());
    }

    // GET: api/animals/5
    [HttpGet("{id:int}")]
    public IActionResult Get(int id)
    {
        var animal = _service.Get(id);
        return animal == null ? NotFound() : Ok(animal);
    }

    // POST: api/animals
    [HttpPost]
    public IActionResult Create([FromBody] AnimalCreateDto dto)
    {
        var created = _service.Create(dto);
        return CreatedAtAction(nameof(Get), new { id = created.Id }, created);
    }

    // PUT: api/animals/5
    [HttpPut("{id:int}")]
    public IActionResult Update(int id, [FromBody] AnimalUpdateDto dto)
    {
        var updated = _service.Update(id, dto);
        return updated == null ? NotFound() : Ok(updated);
    }

    // DELETE: api/animals/5
    [HttpDelete("{id:int}")]
    public IActionResult Delete(int id)
    {
        return _service.Delete(id) ? NoContent() : NotFound();
    }
}

async crud


        using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class AnimalsController : ControllerBase
{
    private readonly IAnimalService _service;

    public AnimalsController(IAnimalService service)
    {
        _service = service;
    }

    // GET: api/animals
    [HttpGet]
    public async Task<IActionResult> GetAll()
    {
        var animals = await _service.GetAllAsync();
        return Ok(animals);
    }

    // GET: api/animals/5
    [HttpGet("{id:int}")]
    public async Task<IActionResult> Get(int id)
    {
        var animal = await _service.GetAsync(id);
        return animal == null ? NotFound() : Ok(animal);
    }

    // POST: api/animals
    [HttpPost]
    public async Task<IActionResult> Create([FromBody] AnimalCreateDto dto)
    {
        var created = await _service.CreateAsync(dto);
        return CreatedAtAction(nameof(Get), new { id = created.Id }, created);
    }

    // PUT: api/animals/5
    [HttpPut("{id:int}")]
    public async Task<IActionResult> Update(int id, [FromBody] AnimalUpdateDto dto)
    {
        var updated = await _service.UpdateAsync(id, dto);
        return updated == null ? NotFound() : Ok(updated);
    }

    // DELETE: api/animals/5
    [HttpDelete("{id:int}")]
    public async Task<IActionResult> Delete(int id)
    {
        bool removed = await _service.DeleteAsync(id);
        return removed ? NoContent() : NotFound();
    }
}

Test the API (URLs)


Assuming it's running on port 5196:

Get all animals
GET http://localhost:5196/api/animals

Get one animal
GET http://localhost:5196/api/animals/1

Create animal
POST http://localhost:5196/api/animals
Content-Type: application/json

{
  "name": "Tigre",
  "age": 5
}

Update animal
PUT http://localhost:5196/api/animals/1
Content-Type: application/json

{
  "name": "Chat Modifié",
  "age": 3
}

Delete animal
DELETE http://localhost:5196/api/animals/1