-
Notifications
You must be signed in to change notification settings - Fork 3
/
PokemonController.cs
74 lines (67 loc) · 1.9 KB
/
PokemonController.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
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace PokemonService
{
[Route("pokemon")]
// [Authorize]
public class PokemonController : Controller
{
private readonly PokemonDbContext dbContext;
//ASP.Net will autowire the constructer from the configured "Services"
public PokemonController(PokemonDbContext dbContext)
{
this.dbContext = dbContext;
}
[HttpGet]
public IEnumerable<Pokemon> Get()
{
return dbContext.Pokemon.ToList();
}
[HttpPost]
public IActionResult Post([FromBody]Pokemon newPokemon)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
dbContext.Pokemon.Add(newPokemon);
dbContext.SaveChanges();
return Ok(newPokemon);
}
[HttpGet("{id}")]
public IActionResult Get(int id)
{
var pokemon = dbContext.Pokemon.Find(id);
if (pokemon == null)
{
return NotFound();
}
return Ok(pokemon);
}
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody]Pokemon pokemon)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
pokemon.Id = id;
dbContext.Pokemon.Update(pokemon);
dbContext.SaveChanges();
return Ok(pokemon);
}
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
var pokemon = dbContext.Pokemon.Find(id);
if(pokemon != null)
{
dbContext.Pokemon.Remove(pokemon);
dbContext.SaveChanges();
}
return Ok();
}
}
}