ASP .NET Core

Teoria e prática

Resumo em construção
Voltar

Material complementar:


Conceito:

Framework web C#, que usa .NET Core. EF Core (Entity Framework Core) é ORM (Object-Relational Mapping) para .NET, instalado via 'dotnet tool install --global dotnet-ef'.



API CRUD .NET 10 básica (Controllers, EF Core, SQL Server, DTOs):

Utiliza-se Visual Studio, criar API web ASP .NET Core, configurações padrão. Projeto 1 do GitHub (acesse).

    Preparando projeto:
  1. Instalar .NET 10, Visual Studio, SQL Server, SQL Server Management Studio
  2. SQL Server Management Studio, localhost, bancos de dados, criar novo banco de dados nome 'CatDB'
  3. Visual Studio / nova solução / criar projeto / API web ASP .NET Core, nome 'CatAPI'
  4. Visual Studio / pasta raíz do projeto / gerenciar pacotes NuGet / instalar pacotes:
    • Scalar.AspNetCore
    • Microsoft.EntityFrameworkCore
    • Microsoft.EntityFrameworkCore.Tools
    • Microsoft.EntityFrameworkCore.SqlServer
  5. Program.cs:
    
    using Microsoft.EntityFrameworkCore;
    using Scalar.AspNetCore;
    using CatAPI.Data;
    using CatAPI.Services;
    
    var builder = WebApplication.CreateBuilder(args);
    
    builder.Services.AddControllers();
    builder.Services.AddOpenApi();
    
    builder.Services.AddDbContext<AppDbContext>(options =>
        options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
    
    builder.Services.AddScoped<ICatService, CatService>();
    
    var app = builder.Build();
    
    if (app.Environment.IsDevelopment())
    {
        app.MapOpenApi();
        app.MapScalarApiReference();
    }
    
    app.UseHttpsRedirection();
    app.UseAuthorization();
    app.MapControllers();
    app.Run();
    
  6. Executar aplicação e acessar: http://localhost:porta/scalar

  7. Implementar Models:
  8. Pasta raíz do projeto, criar pasta "Models"
  9. Models/Cat.cs:
    
    namespace CatAPI.Models;
    
    public class Cat
    {
        public int Id { get; set; }
        public string Name { get; set; } = string.Empty;
        public string Breed { get; set; } = string.Empty;
    }
    

  10. Aplicar DbContext
  11. Pasta raíz do projeto / criar pasta "Data"
  12. Data/AppDbContext.cs:
    
    using Microsoft.EntityFrameworkCore;
    using CatAPI.Models;
    
    namespace CatAPI.Data;
    
    public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
    {
        public DbSet<Cat> Cats => Set<Cat>();
    }
    
  13. appsettings.json:
    
    {
      "ConnectionStrings": {
        "DefaultConnection": "Server=localhost;Database=CatDB;Trusted_Connection=True;TrustServerCertificate=True;"
      },
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "AllowedHosts": "*"
    }
    

  14. DTOs:
  15. Criar pasta "DTOs" na raiz do projeto
  16. DTOs/CreateCatRequest.cs:
    
    namespace CatAPI.Dtos;
    
    public class CreateCatRequest
    {
        public string Name { get; set; } = string.Empty;
        public string Breed { get; set; } = string.Empty;
    }
    
  17. DTOs/UpdateCatRequest.cs:
    
    namespace CatAPI.Dtos;
    
    public class UpdateCatRequest
    {
        public int Id { get; set; }
        public string Name { get; set; } = string.Empty;
        public string Breed { get; set; } = string.Empty;
    }
    
  18. DTOs/CatResponse.cs:
    
    namespace CatAPI.Dtos;
    
    public class CatResponse
    {
        public int Id { get; set; }
        public string Name { get; set; } = string.Empty;
        public string Breed { get; set; } = string.Empty;
    }
    

  19. Implementar Services (Dependency Injection):
  20. Pasta raíz do projeto, criar pasta "Services"
  21. Services/ICatService.cs:
    
    using CatAPI.Dtos;
    
    namespace CatAPI.Services;
    
    public interface ICatService
    {
        Task<List<CatResponse>> GetAllCatsAsync();
        Task<CatResponse?> GetCatByIdAsync(int id);
        Task<CatResponse> AddCatAsync(CreateCatRequest cat);
        Task<bool> UpdateCatAsync(int id, UpdateCatRequest cat);
        Task<bool> DeleteCatAsync(int id);
    }
    
  22. Services/CatService.cs:
    
    using Microsoft.EntityFrameworkCore;
    using CatAPI.Data;
    using CatAPI.Dtos;
    using CatAPI.Models;
    
    namespace CatAPI.Services;
    
    public class CatService(AppDbContext context) : ICatService
    {
        public async Task<CatResponse> AddCatAsync(CreateCatRequest cat)
        {
            var newCat = new Cat
            {
                Name = cat.Name,
                Breed = cat.Breed
            };
    
            context.Cats.Add(newCat);
            await context.SaveChangesAsync();
            return new CatResponse
            {
                Id = newCat.Id,
                Name = newCat.Name,
                Breed = newCat.Breed
            };
        }
    
        public async Task<bool> DeleteCatAsync(int id)
        {
            var catToDelete = await context.Cats.FindAsync(id);
            if (catToDelete is null)
                return false;
    
            context.Cats.Remove(catToDelete);
            await context.SaveChangesAsync();
            return true;
        }
    
        public async Task<List<CatResponse>> GetAllCatsAsync()
            => await context.Cats.Select(c => new CatResponse
            {
                Id = c.Id,
                Name = c.Name,
                Breed = c.Breed
            }).ToListAsync();
    
        public async Task<CatResponse?> GetCatByIdAsync(int id)
        {
            var result = await context.Cats
                .Where(c => c.Id == id)
                .Select(c => new CatResponse
                {
                    Id = c.Id,
                    Name = c.Name,
                    Breed = c.Breed
                })
                .FirstOrDefaultAsync();
    
            return result;
        }
    
        public async Task<bool> UpdateCatAsync(int id, UpdateCatRequest cat)
        {
            var existingCat = await context.Cats.FindAsync(id);
            if (existingCat is null)
                return false;
    
            existingCat.Name = cat.Name;
            existingCat.Breed = cat.Breed;
    
            await context.SaveChangesAsync();
            return true;
        }
    }
    

  23. Implementar Controllers:
  24. Controllers/CatsController.cs (Commom / API Controller / Empty Controller):
    
    using Microsoft.AspNetCore.Mvc;
    using CatAPI.Dtos;
    using CatAPI.Services;
    
    namespace CatAPI.Controllers;
    
    [Route("api/[controller]")]
    [ApiController]
    public class CatsController(ICatService service) : ControllerBase
    {
        [HttpGet]
        public async Task<ActionResult<List<CatResponse>>> GetCats()
            => Ok(await service.GetAllCatsAsync());
    
        [HttpGet("{id}")]
        public async Task<ActionResult<CatResponse>> GetCat(int id)
        {
            var cat = await service.GetCatByIdAsync(id);
            return cat is null ? NotFound("Gato com ID não encontrado") : Ok(cat);
        }
    
        [HttpPost]
        public async Task<ActionResult<CatResponse>> AddCat(CreateCatRequest cat)
        {
            var createdCat = await service.AddCatAsync(cat);
            return CreatedAtAction(nameof(GetCat), new { id = createdCat.Id }, createdCat);
        }
    
        [HttpPut("{id}")]
        public async Task<ActionResult> UpdateCat(int id, UpdateCatRequest cat)
        {
            var updated = await service.UpdateCatAsync(id, cat);
            return updated ? Ok() : NotFound("Gato com ID não encontrado");
        }
    
        [HttpDelete("{id}")]
        public async Task<ActionResult> DeleteCat(int id)
        {
            var deleted = await service.DeleteCatAsync(id);
            return deleted ? NoContent() : NotFound("Gato com ID não encontrado");
        }
    }
    
  25. Visual Studio / abrir console do gerenciador de pacotes
    • Entrar na pasta do projeto: cd nome_do_projeto
    • Adicionar migrations: Add-Migration Initial
    • Atualizar banco de dados: Update-Database
  26. No SQL Server Management Studio, verificar se banco de dados foi criado corretamente

  27. Consumir API:
  28. Executar aplicação e acessar: http://localhost:porta/scalar
  29. Consumir API no Scalar e verificar respostas


API CRUD .NET 10 (EF Core, PostgreSQL e Docker):

Em breve.

Elaborado por Mateus Schwede
ubsocial.github.io