Skip to content

Commit b464312

Browse files
Merge pull request dotnet#208 from sammychinedu2ky/Rdg10
Sample for Rdg10
2 parents e6df776 + e37e2b7 commit b464312

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
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+
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
2+
3+
<PropertyGroup>
4+
<TargetFramework>net8.0</TargetFramework>
5+
<Nullable>enable</Nullable>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<InvariantGlobalization>true</InvariantGlobalization>
8+
<PublishAot>true</PublishAot>
9+
</PropertyGroup>
10+
11+
</Project>

0 commit comments

Comments
 (0)