Web API Controller Example

These are example controller methods by http verb. These can also be async but the context method must return async Task.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Synchronous 
[HttpGet("{id}")]
public ActionResult<ApiGameMoveModel> Get(int id)
{
var model = _context.Select(id);
return model;
}

// Asynchronous
[HttpGet("{id}")]
public async Task<ActionResult><ApiGameMoveModel> Get(int id)
{
var model = await _context.Select(id);
return model;
}

Synchronous methods

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
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using GameUI.Models;

namespace GameUI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ApiGameController : ControllerBase
{
private readonly DummyContext _context;

public ApiGameController(DummyContext context)
{
_context = context;
}

// GET: api/ApiGame
[HttpGet]
public ActionResult<IEnumerable<ApiGameMoveModel>> Get()
{
// TODO ~ use db context to select a list

// TODO ~ if none exist `return NotFound();`

return new JsonResult(new List<ApiGameMoveModel>
{
new ApiGameMoveModel() { Id = 42, Player = "player in list that was selected" },
new ApiGameMoveModel() { Id = 43, Player = "player in list that was selected" }
});
}

// GET: api/ApiGame/5
[HttpGet("{id}")]
public ActionResult<ApiGameMoveModel> Get(int id)
{
// TODO ~ use db context to select on `id`

// TODO ~ check id exists, if it doesnt `return NotFound();`

return new ApiGameMoveModel() { Id = id, Player = $"player that was selected on {id}" };
}

// PUT: api/ApiGame/5
[HttpPut("{id}")]
public IActionResult Put(int id, ApiGameMoveModel apiGameMoveModel)
{
if (id != apiGameMoveModel.Id)
return BadRequest();

// TODO ~ check id exists, if it doesnt `return NotFound();`

// TODO ~ use db context to update

return NoContent();
}

// POST: api/ApiGame
[HttpPost]
public IActionResult Post(ApiGameMoveModel apiGameMoveModel)
{
// TODO ~ use db context to update

var response = new ApiGameMoveModel
{
Id = 42,
Player = "player that was updated"
};
return new JsonResult(response);
}

// DELETE: api/ApiGame/5
[HttpDelete("{id}")]
public ActionResult<ApiGameMoveModel> Delete(int id)
{
// TODO ~ use db context to select on `id`
// if not found, return NotFound();

// TODO ~ use db context to do the delete

// TODO ~ return the model selected by `id`
return new ApiGameMoveModel(){ Id = id, Player = "player that was deleted" };
}
}
}