-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathProgram.cs
More file actions
105 lines (84 loc) · 2.58 KB
/
Copy pathProgram.cs
File metadata and controls
105 lines (84 loc) · 2.58 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
class Program
{
static async Task Main(string[] args)
{
var app = WebApplication.Create(args);
app.MapGet("/api/todos", GetTodos);
app.MapGet("/api/todos/{id}", GetTodo);
app.MapPost("/api/todos", CreateTodo);
app.MapPost("/api/todos/{id}", UpdateCompleted);
app.MapDelete("/api/todos/{id}", DeleteTodo);
await app.RunAsync();
}
static async Task GetTodos(HttpContext http)
{
using var db = new TodoDbContext();
var todos = await db.Todos.ToListAsync();
await http.Response.WriteJsonAsync(todos);
}
static async Task GetTodo(HttpContext http)
{
if (!http.Request.RouteValues.TryGet("id", out int id))
{
http.Response.StatusCode = 400;
return;
}
using var db = new TodoDbContext();
var todo = await db.Todos.FindAsync(id);
if (todo == null)
{
http.Response.StatusCode = 404;
return;
}
await http.Response.WriteJsonAsync(todo);
}
static async Task CreateTodo(HttpContext http)
{
var todo = await http.Request.ReadJsonAsync<TodoItem>();
using var db = new TodoDbContext();
await db.Todos.AddAsync(todo);
await db.SaveChangesAsync();
http.Response.StatusCode = 204;
}
static async Task UpdateCompleted(HttpContext http)
{
if (!http.Request.RouteValues.TryGet("id", out int id))
{
http.Response.StatusCode = 400;
return;
}
using var db = new TodoDbContext();
var todo = await db.Todos.FindAsync(id);
if (todo == null)
{
http.Response.StatusCode = 404;
return;
}
var inputTodo = await http.Request.ReadJsonAsync<TodoItem>();
todo.IsComplete = inputTodo.IsComplete;
await db.SaveChangesAsync();
http.Response.StatusCode = 204;
}
static async Task DeleteTodo(HttpContext http)
{
if (!http.Request.RouteValues.TryGet("id", out int id))
{
http.Response.StatusCode = 400;
return;
}
using var db = new TodoDbContext();
var todo = await db.Todos.FindAsync(id);
if (todo == null)
{
http.Response.StatusCode = 404;
return;
}
db.Todos.Remove(todo);
await db.SaveChangesAsync();
http.Response.StatusCode = 204;
}
}