Merge pull request #204 from sammychinedu2ky/Rdg9

Added Sample for RDG009
pull/205/head
Rick Anderson 2023-10-02 08:36:32 -10:00 committed by GitHub
commit 37af9cf858
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 115 additions and 0 deletions

View File

@ -0,0 +1,95 @@
#define RDG009 //RDG009F
#if NEVER
#elif RDG009
// <snippet_1>
using System.Text.Json.Serialization;
var builder = WebApplication.CreateSlimBuilder();
var todos = new[]
{
new Todo(1, "Write tests", DateTime.UtcNow.AddDays(2)),
new Todo(2, "Fix tests",DateTime.UtcNow.AddDays(1))
};
builder.Services.AddSingleton(todos);
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonSerializerContext.Default);
});
var app = builder.Build();
app.MapGet("/v1/todos/{id}", ([AsParameters] TodoItemRequest request) =>
{
return request.todos.ToList().Find(todoItem => todoItem.Id == request.Id)
is Todo todo
? Results.Ok(todo)
: Results.NotFound();
});
app.Run();
struct TodoItemRequest
{
public int Id { get; set; }
[AsParameters]
public Todo[] todos { get; set; }
}
internal record Todo(int Id, string Task, DateTime DueDate);
[JsonSerializable(typeof(Todo[]))]
internal partial class AppJsonSerializerContext : JsonSerializerContext
{
}
// </snippet_1>
#elif RDG009F
// <snippet_1f>
using System.Text.Json.Serialization;
var builder = WebApplication.CreateSlimBuilder();
var todos = new[]
{
new Todo(1, "Write tests", DateTime.UtcNow.AddDays(2)),
new Todo(2, "Fix tests",DateTime.UtcNow.AddDays(1))
};
builder.Services.AddSingleton(todos);
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonSerializerContext.Default);
});
var app = builder.Build();
app.MapGet("/v1/todos/{id}", ([AsParameters] TodoItemRequest request) =>
{
return request.todos.ToList().Find(todoItem => todoItem.Id == request.Id)
is Todo todo
? Results.Ok(todo)
: Results.NotFound();
});
app.Run();
struct TodoItemRequest
{
public int Id { get; set; }
public Todo[] todos { get; set; }
}
internal record Todo(int Id, string Task, DateTime DueDate);
[JsonSerializable(typeof(Todo[]))]
internal partial class AppJsonSerializerContext : JsonSerializerContext
{
}
// </snippet_1f>
#endif

View File

@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<PublishAot>true</PublishAot>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}