Is it possible to have a request class where it is possible to declare the minimal API request parameters in .NET 6? I know that a similar feature will be provided by .NET 7.
What I am trying to achieve is the following:
public class GetProductByIdRequestDto
{
[FromRoute(Name = "id")] public string Id { get; set; }
}
app.MapGet("/products/{id}", GetProductByIdRequestDto request => HandleRequest(request));
The problem is that:
- If I don't declare any attribute AspNet automatically inferres that it should be from body and this causes an error since it's a GET request
- If I use the [FromRoute] in the MapGet delegate AspNet throws an error because there is no route parameter named "request"
I know that
app.MapGet("/products/{id}", [FromRoute(Name = "id")]string productId => HandleRequest(productId));
would work, but this is not what I'm looking for
CodePudding user response:
AFAIK there are no out of the box option for it. You can leverage custom parameter binding via TryParse
or BindAsync
:
public class GetProductByIdRequestDto
{
public string Id { get; set; }
public static ValueTask<GetProductByIdRequestDto?> BindAsync(HttpContext context,
ParameterInfo parameter)
{
const string idKey = "id";
var result = new GetProductByIdRequestDto
{
Id = context.Request.RouteValues[idKey]?.ToString()
};
return ValueTask.FromResult<GetProductByIdRequestDto?>(result);
}
}