-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
66 lines (50 loc) · 1.83 KB
/
Program.cs
File metadata and controls
66 lines (50 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using TodoApi.Models;
using TodoApi.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.MapGet("/api/todos", async ([FromServices] AppDbContext db) =>
await db.TodoItems.AsNoTracking().ToListAsync());
app.MapGet("/api/todos/{id:int}", async (int id, [FromServices] AppDbContext db) =>
await db.TodoItems.FindAsync(id)
is TodoItem todo
? Results.Ok(todo)
: Results.NotFound());
app.MapPost("/api/todos", async (TodoItem todo, [FromServices] AppDbContext db) =>
{
db.TodoItems.Add(todo);
await db.SaveChangesAsync();
return Results.Created($"/api/todos/{todo.Id}", todo);
});
app.MapPut("/api/todos/{id:int}", async (int id, TodoItem input, [FromServices] AppDbContext db) =>
{
var todo = await db.TodoItems.FindAsync(id);
if (todo is null) return Results.NotFound();
todo.Title = input.Title;
todo.IsCompleted = input.IsCompleted;
await db.SaveChangesAsync();
return Results.NoContent();
});
app.MapDelete("/api/todos/{id:int}", async (int id, [FromServices] AppDbContext db) =>
{
var todo = await db.TodoItems.FindAsync(id);
if (todo is null) return Results.NotFound();
db.TodoItems.Remove(todo);
await db.SaveChangesAsync();
return Results.NoContent();
});
app.Run();