-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
91 lines (67 loc) · 3.08 KB
/
Program.cs
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
using Microsoft.EntityFrameworkCore;
namespace SuperHeroMinimalAPI
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<DataContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
var app = builder.Build();
//use swagger middleware
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
async Task<List<SuperHero>> GetSuperHeroes(DataContext context) =>
await context.SuperHeroes.ToListAsync();
app.MapGet("/", () => "Hello Minimal API!");
app.MapGet("/superhero", async (DataContext context) =>
await context.SuperHeroes.ToListAsync());
app.MapGet("/superhero/{id}", async (DataContext context, int id) =>
await context.SuperHeroes.FindAsync(id) is SuperHero hero ?
Results.Ok(hero) :
Results.NotFound("Hero under progress /"));
app.MapPost("/superhero", async (DataContext datacontext, SuperHero hero) =>
{
await datacontext.SuperHeroes.AddAsync(hero);
await datacontext.SaveChangesAsync();
return Results.Ok(await GetSuperHeroes(datacontext));
});
app.MapPut("/superhero", async (DataContext context, SuperHero hero, int id) =>
{
var dbhero = await context.SuperHeroes.FindAsync(id);
if (dbhero is null)
{
return Results.NotFound("Hero under progress /");
}
dbhero.FirstName = hero.FirstName;
dbhero.LastName = hero.LastName;
dbhero.HeroName = hero.HeroName;
await context.SaveChangesAsync();
return Results.Ok(await GetSuperHeroes(context));
});
//minimap api call to delete a hero
app.MapDelete("/superhero/{id}", async (DataContext context, int id) =>
{
var dbhero = await context.SuperHeroes.FindAsync(id);
if (dbhero is null)
{
return Results.NotFound("Hero under progress /");
}
context.SuperHeroes.Remove(dbhero);
await context.SaveChangesAsync();
return Results.Ok(await GetSuperHeroes(context));
});
app.Run();
}
}
}