2.1. GamesEndpoints
using System;
using GameStore.Api.Dtos;
namespace GameStore.Api.Endpoints;
public static class GamesEndpoint
{
const string EndpointName = "GetGame";
private static readonly List<GameDto> games = [
new (1, "Street Fighter 2", "Fighting", 19.99M, new DateOnly(1992, 7, 15)),
new (2, "Placeholder Game A", "Action", 29.99M, new DateOnly(2000, 1, 1)),
new (3, "Placeholder Game B", "Adventure", 39.99M, new DateOnly(2001, 2, 2)),
new (4, "Placeholder Game C", "RPG", 49.99M, new DateOnly(2002, 3, 3)),
new (5, "Placeholder Game D", "Shooter", 59.99M, new DateOnly(2003, 4, 4)),
new (6, "Placeholder Game E", "Puzzle", 9.99M, new DateOnly(2004, 5, 5)),
new (7, "Placeholder Game F", "Sports", 19.99M, new DateOnly(2005, 6, 6)),
new (8, "Placeholder Game G", "Racing", 29.99M, new DateOnly(2006, 7, 7)),
new (9, "Placeholder Game H", "Strategy", 39.99M, new DateOnly(2007, 8, 8)),
new (10, "Placeholder Game I", "Simulation", 49.99M, new DateOnly(2008, 9, 9))
];
public static void MapGamesEndpoints(this WebApplication app)
{
var group = app.MapGroup("/games");
group.MapGet("/", () => games);
// GET /games/1
group.MapGet("/{id}", (int id) =>
{
var game = games.Find(game => game.Id ==id);
return game is null ? Results.NotFound() : Results.Ok(game);
}).WithName(EndpointName);
group.MapPost("/", (CreateGameDto newGame) =>
{
GameDto game = new(
games.Count + 1,
newGame.Name,
newGame.Genre,
newGame.Price,
newGame.ReleaseDate
);
games.Add(game);
return Results.CreatedAtRoute(EndpointName, new {id = game.Id}, game);
});
// PUT /games/1
group.MapPut("/{id}", (int id, UpdateGameDto updatedGame) =>
{
var index = games.FindIndex(game => game.Id == id);
if (index == -1)
{
return Results.NotFound();
}
games[index] = new GameDto(
id,
updatedGame.Name,
updatedGame.Genre,
updatedGame.Price,
updatedGame.ReleaseDate
);
return Results.NoContent();
});
// DELETE /games/1
group.MapDelete("/{id}", (int id) =>
{
games.RemoveAll(game => game.Id == id);
return Results.NoContent();
});
}
}
- This Web application app is defined as an extension method on
WebApplication inside the GameStore.Api.Endpoints namespace.
2.2. Data Annotation
- using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations;
namespace GameStore.Api.Dtos;
public record CreateGameDto(
[Required][StringLength(50)] string Name,
[Required][StringLength(20)] string Genre,
[Range(1,100)] decimal Price,
DateOnly ReleaseDate
);
- It is similar to validation in NestJS.