I was reading this article regarding controller action return types, and these two caught my eye.
1.
[HttpGet("{id}")]
[ProducesResponseType<Product>(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IResult GetById(int id)
{
var product = _productContext.Products.Find(id);
return product == null ? Results.NotFound() : Results.Ok(product);
}
[HttpGet("{id}")]
public Results<NotFound, Ok<Product>> GetById(int id)
{
var product = _productContext.Products.Find(id);
return product == null ? TypedResults.NotFound() : TypedResults.Ok(product);
}
Running the sample code, I noticed that for the second method, the possible responses and schemas are missing in Swagger UI, just a single 200 OK
. However, I can see everything just fine on the first method. Only after adding [ProducesResponseType]
attributes on the second method I can see the possible responses and schemas.
At the same time, the article says that with the Results<TResult1, TResultN>
approach (second method):
All the
[ProducesResponseType]
attributes can be excluded, since theHttpResult
implementation contributes automatically to the endpoint metadata.
When multiple
IResult
return types are needed, returningResults<TResult1, TResultN>
is preferred over returningIResult
. ReturningResults<TResult1, TResultN>
is preferred because generic union types automatically retain the endpoint metadata.
What am I missing here? Am I misunderstanding the article?