'Cannot add [FromHeader] attribute for a model/class in ASP.NET Core 6.0 minimal api

I'm trying to add multiple custom headers in the .NET core minimal API, so I added [FromHeader] attribute in front of input parameters.

It's working fine, I can see those headers in swagger.

But I'm looking for a better way to keep all these headers into a class/model and trying to add that in the API header by using [FromHeader] attribute in front of that model.

In this way, I'm getting this error

No public static bool method found for headers Testheader.tryparse(string,out TestHeaders) method found for

This is the code:

app.MapPost("api/v1/testapi",async([FromHeader] TestHeaderModel headers,{
    return Results.Ok(null)
})
.WithTags(new string[]{"test"})
.Produces<response>(200);

Model

public class TestHeaderModel
{
    [FromHeader]
    public string header1 {get;set;}
    [FromHeader]
    public string header2{get;set;}
}

My question: is there any way to keep all these headers in a single class/model and add [FromHeader] attribute for that particular class in the controller?

This approach is working in previous .net core versions, but not in 6.0, Is there any specific reason for that? or I'm missing anything here?



Solution 1:[1]

Take a look at this repository DamianEdwards/MinimalApiPlayground

More specifically this MapGet at this line: https://github.com/DamianEdwards/MinimalApiPlayground/blob/main/src/MinimalApiPlayground/Program.cs#L244

Notice how they are binding an object to a GET method. In that example to query parameters, but might as well be to headers.

That project is using this package (right now in pre-release) MinimalApis.Extensions

https://github.com/DamianEdwards/MinimalApis.Extensions

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Urielzen