Skip to content

Instantly share code, notes, and snippets.

@felipebastosweb
Last active April 3, 2025 14:46
Show Gist options
  • Save felipebastosweb/053d7d7841c6e059a3f0e40852730e64 to your computer and use it in GitHub Desktop.
Save felipebastosweb/053d7d7841c6e059a3f0e40852730e64 to your computer and use it in GitHub Desktop.
AspNet Core API mínima para rodar
/*
Vá em connected services e crie a conexão com o banco de dados LocalDB antes de continuar
Você vai precisar dos dados da conexão para colocar aqui
Ambiente necessário para migrations:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
*/
using Microsoft.EntityFrameworkCore;
using WebAPI.Entities;
namespace WebAPI.Contexts
{
public class MyAppContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Project> Projects { get; set; }
// Esse construtor é indispensável mesmo que a documentação da Microsoft não fale sobre isso
public MyAppContext(DbContextOptions<MyAppContext> options) : base(options)
{
}
// Esse método é insdispensável mesmo que já exista uma conexão pela string de conexão (não é opcional como o GPT fala no comentário)
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Opcional: Use esta configuração apenas se você precisar configurar algo diretamente.
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=nome-do-database;Trusted_Connection=True;MultipleActiveResultSets=true");
}
}
}
}
/*
Criação de migrations:
dotnet ef migrations add InitialCreate
Criação do banco de dados:
dotnet ef update
*/
using Microsoft.EntityFrameworkCore;
using WebAPI.Contexts;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Estava tendo problemas com certificado e esse comando abaixo força a aplicação a usar o certificado
// Configure Kestrel to use a specific certificate
builder.WebHost.ConfigureKestrel(options =>
{
// forçando portas durante desenvolvimento, mas inadequado para produção com escalabilidade
options.ListenAnyIP(8088);
options.ListenAnyIP(7054, listenOptions =>
{
listenOptions.UseHttps();
});
});
// Por se tratar de uma API precisei incluir CORS para fazer, até mesmo, uma consulta direta no navegador
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
});
// Configurando o DbContext com o provedor do banco de dados SQL Server (os dados vão no arquivo secrets)
builder.Services.AddDbContext<MyAppContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DatabaseConnection")));
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseCors("AllowAll");
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
// Ao executar a aplicação as APIs ficarão disponíveis nas urls https://localhost:7054/api/users e https://localhost:7054/api/projects
namespace WebAPI.Entities
{
public class Project
{
public Guid Id { get; set; }
public Guid? UserId { get; set; }
public User? User { get; set; }
public string? Title { get; set; }
public string? Description { get; set; }
public string? Objective { get; set; }
public DateTime StartDate { get; set; }
public DateTime FinishDate { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public DateTime ArquivedAt { get; set; }
}
}
/*
Código gerado usando:
Adicionar -> Novo item com scaffold -> Controlador API com ações, usando o Entity framework
Classe de modelo: User
Classe DbContext: MyDbContext
Nome do Controlador: UsersController
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebAPI.Contexts;
using WebAPI.Entities;
namespace WebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProjectsController : ControllerBase
{
private readonly MyAppContext _context;
public ProjectsController(MyAppContext context)
{
_context = context;
}
// GET: api/Projects
[HttpGet]
public async Task<ActionResult<IEnumerable<Project>>> GetProjects()
{
return await _context.Projects.ToListAsync();
}
// GET: api/Projects/5
[HttpGet("{id}")]
public async Task<ActionResult<Project>> GetProject(Guid id)
{
var project = await _context.Projects.FindAsync(id);
if (project == null)
{
return NotFound();
}
return project;
}
// PUT: api/Projects/5
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPut("{id}")]
public async Task<IActionResult> PutProject(Guid id, Project project)
{
if (id != project.Id)
{
return BadRequest();
}
_context.Entry(project).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProjectExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/Projects
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<Project>> PostProject(Project project)
{
_context.Projects.Add(project);
await _context.SaveChangesAsync();
return CreatedAtAction("GetProject", new { id = project.Id }, project);
}
// DELETE: api/Projects/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteProject(Guid id)
{
var project = await _context.Projects.FindAsync(id);
if (project == null)
{
return NotFound();
}
_context.Projects.Remove(project);
await _context.SaveChangesAsync();
return NoContent();
}
private bool ProjectExists(Guid id)
{
return _context.Projects.Any(e => e.Id == id);
}
}
}
namespace WebAPI.Entities
{
public class User
{
public Guid Id { get; set; }
public string? Username { get; set; }
public string? PasswordHash { get; set; }
public string? Email { get; set; }
public string? Telephone { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public DateTime ArquivedAt { get; set; }
}
}
/*
Código gerado usando:
Adicionar -> Novo item com scaffold -> Controlador API com ações, usando o Entity framework
Classe de modelo: User
Classe DbContext: MyDbContext
Nome do Controlador: UsersController
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebAPI.Contexts;
using WebAPI.Entities;
namespace WebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
private readonly MyAppContext _context;
public UsersController(MyAppContext context)
{
_context = context;
}
// GET: api/Users
[HttpGet]
public async Task<ActionResult<IEnumerable<User>>> GetUsers()
{
return await _context.Users.ToListAsync();
}
// GET: api/Users/5
[HttpGet("{id}")]
public async Task<ActionResult<User>> GetUser(Guid id)
{
var user = await _context.Users.FindAsync(id);
if (user == null)
{
return NotFound();
}
return user;
}
// PUT: api/Users/5
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPut("{id}")]
public async Task<IActionResult> PutUser(Guid id, User user)
{
if (id != user.Id)
{
return BadRequest();
}
_context.Entry(user).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!UserExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/Users
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<User>> PostUser(User user)
{
_context.Users.Add(user);
await _context.SaveChangesAsync();
return CreatedAtAction("GetUser", new { id = user.Id }, user);
}
// DELETE: api/Users/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteUser(Guid id)
{
var user = await _context.Users.FindAsync(id);
if (user == null)
{
return NotFound();
}
_context.Users.Remove(user);
await _context.SaveChangesAsync();
return NoContent();
}
private bool UserExists(Guid id)
{
return _context.Users.Any(e => e.Id == id);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment