ASP .NET Core

Conceitos e exemplo prático
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 'VideoGameCharacterDb'
  3. Visual Studio / nova solução / criar projeto / API web ASP .NET Core
  4. Visual Studio / pasta raíz do projeto / gerenciar pacotes NuGet / instalar Scalar.AspNetCore
  5. Program.cs:
    
    using Microsoft.EntityFrameworkCore;
    using Scalar.AspNetCore;
    using VideoGameCharacterApi.Data;
    using VideoGameCharacterApi.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<IVideoGameCharacterService, VideoGameCharacterService>();
    
    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/Character.cs:
    
    namespace VideoGameCharacterApi.Models;
    
    public class Character
    {
        public int Id { get; set; }
        public string Name { get; set; } = string.Empty;
        public string Game { get; set; } = string.Empty;
        public string Role { get; set; } = string.Empty;
    }
    

  10. Implementar Controllers:
  11. Controllers/VideoGameCharactersController.cs (Commom / API Controller / Empty Controller):
    
    using Microsoft.AspNetCore.Mvc;
    using VideoGameCharacterApi.Dtos;
    using VideoGameCharacterApi.Services;
    
    namespace VideoGameCharacterApi.Controllers;
    
    [Route("api/[controller]")]
    [ApiController]
    public class VideoGameCharactersController(IVideoGameCharacterService service) : ControllerBase
    {
        [HttpGet]
        public async Task<ActionResult<List<CharacterResponse>>> GetCharacters()
            => Ok(await service.GetAllCharactersAsync());
    
        [HttpGet("{id}")]
        public async Task<ActionResult<CharacterResponse>> GetCharacter(int id)
        {
            var character = await service.GetCharacterByIdAsync(id);
            return character is null ? NotFound("Character with the given Id was not found.") : Ok(character);
        }
    
        [HttpPost]
        public async Task<ActionResult<CharacterResponse>> AddCharacter(CreateCharacterRequest character)
        {
            var createdCharacter = await service.AddCharacterAsync(character);
            return CreatedAtAction(nameof(GetCharacter), new { id = createdCharacter.Id }, createdCharacter);
        }
    
        [HttpPut("{id}")]
        public async Task<ActionResult> UpdateCharacter(int id, UpdateCharacterRequest character)
        {
            var updated = await service.UpdateCharacterAsync(id, character);
            return updated ? Ok() : NotFound("Character with the given Id was not found.");
        }
    
        [HttpDelete("{id}")]
        public async Task<ActionResult> DeleteCharacter(int id)
        {
            var deleted = await service.DeleteCharacterAsync(id);
            return deleted ? NoContent() : NotFound("Character with the given Id was not found.");
        }
    }
    

  12. Implementar Services (Dependency Injection):
  13. Pasta raíz do projeto, criar pasta "Services"
  14. Services/IVideoGameCharacterService.cs:
    
    using VideoGameCharacterApi.Dtos;
    
    namespace VideoGameCharacterApi.Services;
    
    public interface IVideoGameCharacterService
    {
        Task<List<CharacterResponse>> GetAllCharactersAsync();
        Task<CharacterResponse?> GetCharacterByIdAsync(int id);
        Task<CharacterResponse> AddCharacterAsync(CreateCharacterRequest character);
        Task<bool> UpdateCharacterAsync(int id, UpdateCharacterRequest character);
        Task<bool> DeleteCharacterAsync(int id);
    }
    
  15. Services/VideoGameCharacterService.cs:
    
    using Microsoft.EntityFrameworkCore;
    using VideoGameCharacterApi.Data;
    using VideoGameCharacterApi.Dtos;
    using VideoGameCharacterApi.Models;
    
    namespace VideoGameCharacterApi.Services;
    
    public class VideoGameCharacterService(AppDbContext context) : IVideoGameCharacterService
    {
        public async Task<CharacterResponse> AddCharacterAsync(CreateCharacterRequest character)
        {
            var newCharacter = new Character
            {
                Name = character.Name,
                Game = character.Game,
                Role = character.Role
            };
    
            context.Characters.Add(newCharacter);
            await context.SaveChangesAsync();
    
            return new CharacterResponse
            {
                Id = newCharacter.Id,
                Name = newCharacter.Name,
                Game = newCharacter.Game,
                Role = newCharacter.Role
            };
        }
    
        public async Task<bool> DeleteCharacterAsync(int id)
        {
            var characterToDelete = await context.Characters.FindAsync(id);
            if (characterToDelete is null)
                return false;
    
            context.Characters.Remove(characterToDelete);
            await context.SaveChangesAsync();
    
            return true;
        }
    
        public async Task<List<CharacterResponse>> GetAllCharactersAsync()
            => await context.Characters.Select(c => new CharacterResponse
            {
                Id = c.Id,
                Name = c.Name,
                Game = c.Game,
                Role = c.Role
            }).ToListAsync();
    
        public async Task<CharacterResponse?> GetCharacterByIdAsync(int id)
        {
            var result = await context.Characters
                .Where(c => c.Id == id)
                .Select(c => new CharacterResponse
                {
                    Id = c.Id,
                    Name = c.Name,
                    Game = c.Game,
                    Role = c.Role
                })
                .FirstOrDefaultAsync();
    
            return result;
        }
    
        public async Task<bool> UpdateCharacterAsync(int id, UpdateCharacterRequest character)
        {
            var existingCharacter = await context.Characters.FindAsync(id);
            if (existingCharacter is null)
                return false;
    
            existingCharacter.Name = character.Name;
            existingCharacter.Game = character.Game;
            existingCharacter.Role = character.Role;
    
            await context.SaveChangesAsync();
    
            return true;
        }
    }
    

  16. EF Core:
  17. Visual Studio / pasta raíz do projeto / gerenciar pacotes NuGet / instalar Microsoft.EntityFrameworkCore
  18. Visual Studio / pasta raíz do projeto / gerenciar pacotes NuGet / instalar Microsoft.EntityFrameworkCore.Tools
  19. Visual Studio / pasta raíz do projeto / gerenciar pacotes NuGet / instalar Microsoft.EntityFrameworkCore.SqlServer

  20. Aplicar DbContext
  21. Pasta raíz do projeto / criar pasta "Data"
  22. Data/AppDbContext.cs:
    
    using Microsoft.EntityFrameworkCore;
    using VideoGameCharacterApi.Models;
    
    namespace VideoGameCharacterApi.Data;
    
    public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
    {
        public DbSet<Character> Characters => Set<Character>();
    }
    
  23. appsettings.json:
    
    {
      "ConnectionStrings": {
        "DefaultConnection": "Server=localhost;Database=VideoGameCharacterDb;Trusted_Connection=True;TrustServerCertificate=True;"
      },
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "AllowedHosts": "*"
    }
    
  24. 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
  25. No SQL Server Management Studio, verificar se banco de dados foi criado corretamente

  26. DTOs:
  27. Criar pasta "DTOs" na raiz do projeto
  28. DTOs/CreateCharacterRequest.cs:
    
    namespace VideoGameCharacterApi.Dtos;
    
    public class CreateCharacterRequest
    {
        public string Name { get; set; } = string.Empty;
        public string Game { get; set; } = string.Empty;
        public string Role { get; set; } = string.Empty;
    }
    
  29. DTOs/UpdateCharacterRequest.cs:
    
    namespace VideoGameCharacterApi.Dtos;
    
    public class UpdateCharacterRequest
    {
        public int Id { get; set; }
        public string Name { get; set; } = string.Empty;
        public string Game { get; set; } = string.Empty;
        public string Role { get; set; } = string.Empty;
    }
    
  30. DTOs/CharacterResponse.cs:
    
    namespace VideoGameCharacterApi.Dtos;
    
    public class CharacterResponse
    {
        public int Id { get; set; }
        public string Name { get; set; } = string.Empty;
        public string Game { get; set; } = string.Empty;
        public string Role { get; set; } = string.Empty;
    }
    

  31. Consumir API:
  32. Executar aplicação e acessar: http://localhost:porta/scalar
  33. 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