Support for AsParameters /2 (#29585)

* generics in What's new /2

* generics in What's new /2
pull/29586/head
Rick Anderson 2023-06-20 16:09:58 -10:00 committed by GitHub
parent f23b174b82
commit 3e4504bd69
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 53 additions and 0 deletions

View File

@ -160,6 +160,19 @@ The main entry points to subsystems that don't work reliably with native AOT are
:::image type="content" source="../fundamentals/aot/_static/top-level-annnotations.png" alt-text="Visual Studio window showing IL2026 warning message on the AddControllers method that says MVC doesn't currently support native AOT.":::
### Support for AsParameters and automatic metadata generation
In this preview, minimal APIs generated at compile-time include support for parameters decorated with the [`[AsParameters]`](xref:Microsoft.AspNetCore.Http.AsParametersAttribute) attribute and support automatic metadata inference for request and response types. Consider the following code:
:::code language="csharp" source="~/release-notes/sample/ProgramAsParameters.cs" highlight="22":::
The preceding generated code:
* Binds a `projectId` parameter from the query.
* Binds a `Todo` parameter from the JSON body.
* Annotates the endpoint metadata to indicate that it accepts a JSON payload.
* Annotate the endpoint metadata to indicate that it returns a Todo as a JSON payload.
## Miscellaneous
### HTTP/3 enabled by default

View File

@ -0,0 +1,40 @@
using System.Text.Json.Serialization;
using MyFirstAotWebApi;
var builder = WebApplication.CreateSlimBuilder(args);
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonSerializerContext.Default);
});
var app = builder.Build();
var sampleTodos = TodoGenerator.GenerateTodos().ToArray();
var todosApi = app.MapGroup("/todos");
todosApi.MapGet("/", () => sampleTodos);
todosApi.MapGet("/{id}", (int id) =>
sampleTodos.FirstOrDefault(a => a.Id == id) is { } todo
? Results.Ok(todo)
: Results.NotFound());
app.MapPost("/todos", ([AsParameters] CreateTodoArgs payload) =>
{
if (payload.TodoToCreate is not null)
{
return payload.TodoToCreate;
}
return new Todo(0, "New todo", DateTime.Now, false);
});
app.Run();
[JsonSerializable(typeof(Todo[]))]
internal partial class AppJsonSerializerContext : JsonSerializerContext
{
}
record CreateTodoArgs(int ProjectId, Todo? TodoToCreate);
record Todo(int Id, string Name, DateTime CreatedAt, bool IsCompleted);