Program.cs 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. using System.Text.Json.Serialization;
  2. var builder = WebApplication.CreateSlimBuilder(args);
  3. builder.Services.ConfigureHttpJsonOptions(options =>
  4. {
  5. options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonSerializerContext.Default);
  6. });
  7. var app = builder.Build();
  8. var sampleTodos = new Todo[] {
  9. new(1, "Walk the dog"),
  10. new(2, "Do the dishes", DateOnly.FromDateTime(DateTime.Now)),
  11. new(3, "Do the laundry", DateOnly.FromDateTime(DateTime.Now.AddDays(1))),
  12. new(4, "Clean the bathroom"),
  13. new(5, "Clean the car", DateOnly.FromDateTime(DateTime.Now.AddDays(2)))
  14. };
  15. var todosApi = app.MapGroup("/todos");
  16. todosApi.MapGet("/", () => sampleTodos);
  17. todosApi.MapGet("/{id}", (int id) =>
  18. sampleTodos.FirstOrDefault(a => a.Id == id) is { } todo
  19. ? Results.Ok(todo)
  20. : Results.NotFound());
  21. app.Run();
  22. public record Todo(int Id, string? Title, DateOnly? DueBy = null, bool IsComplete = false);
  23. [JsonSerializable(typeof(Todo[]))]
  24. internal partial class AppJsonSerializerContext : JsonSerializerContext
  25. {
  26. }