Even though it was introduced in .NET 7, I came across recently the AsParametersAttribute
. Let's have a look what it is good for.
Organinzing paramters
Let's have a look at the following Minimal API:
app.MapGet("/test/{id:int}/{name}", (int id, string name, [FromQuery(Name="foo")] string bar) => id);
We have three parameters scattered around the method signature. It is not a big deal for this simple example, but it can get messy with more parameters (and services).
So we can use the AsParameters
attribute to group them together:
// Use the attribute in front of your entity
app.MapGet("/test/{id:int}/{name}", ([AsParameters]TestRequestDto dto) => dto.Id);
// Could also be a regular class, struct or record struct
public record TestRequestDto(int Id, string Name, [FromQuery(Name="foo")] string Bar);
Now everything is encapsulated in the TestRequestDto
and the method signature is much cleaner. A small drawback is that there can be a very small overhead in performance (like measurable not necessarily noticable) and allocations (if you take a class).