|
| 1 | +using System.Text.Json.Serialization; |
| 2 | + |
| 3 | +var builder = WebApplication.CreateSlimBuilder(); |
| 4 | +var todos = new[] |
| 5 | +{ |
| 6 | + new Todo(1, "Write tests"), |
| 7 | + new Todo(2, "Fix tests") |
| 8 | +}; |
| 9 | + |
| 10 | +builder.Services.AddSingleton(todos); |
| 11 | + |
| 12 | +builder.Services.ConfigureHttpJsonOptions(options => |
| 13 | +{ |
| 14 | + options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonSerializerContext.Default); |
| 15 | +}); |
| 16 | + |
| 17 | +var app = builder.Build(); |
| 18 | + |
| 19 | + |
| 20 | +app.MapGet("/v1/todos/{id?}", (int? Id, Todo[] todos) => |
| 21 | +{ |
| 22 | + if (Id.HasValue) |
| 23 | + { |
| 24 | + return todos.ToList().Find(todoItem => todoItem.Id == Id) |
| 25 | + is Todo todo |
| 26 | + ? Results.Ok(todo) |
| 27 | + : Results.NotFound(); |
| 28 | + } |
| 29 | + else |
| 30 | + { |
| 31 | + return Results.Ok(todos); |
| 32 | + } |
| 33 | + |
| 34 | +}); |
| 35 | + |
| 36 | +app.Run(); |
| 37 | + |
| 38 | + |
| 39 | +public class Todo |
| 40 | +{ |
| 41 | + public DateTime DueDate { get; } |
| 42 | + public int Id { get; private set; } |
| 43 | + public string Task { get; private set; } |
| 44 | + |
| 45 | + // Additional constructors |
| 46 | + public Todo(int Id, string Task, DateTime DueDate) |
| 47 | + |
| 48 | + { |
| 49 | + this.Id = Id; |
| 50 | + this.Task = Task; |
| 51 | + this.DueDate = DueDate; |
| 52 | + } |
| 53 | + |
| 54 | + public Todo(int Id, string Task) |
| 55 | + : this(Id, Task, default) |
| 56 | + { |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +[JsonSerializable(typeof(Todo[]))] |
| 61 | +internal partial class AppJsonSerializerContext : JsonSerializerContext |
| 62 | +{ |
| 63 | +} |
| 64 | + |
0 commit comments