Using CreatedAtAction with ActionResult<T>
In my mind, the biggest advantage of using ActionResult<T> is making unit tests much cleaner. If I used this document's example CreateAsync method in a unit test, my result object's Value property would be null, and its Result property would be set. If I wanted to verify that I am returning the product object as the value from this method, I would have to do something like ((CreatedAtActionResult)result.Result).Value as Product in order to actually get the value back. This defeats the purpose of using ActionResult<T> and actually makes it more complicated than using IActionResult. Is there a way to return a 201 status with ActionResult<T> without making my unit tests horrible?
Document Details
⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.
- ID: fa03501b-5e71-4c18-0269-39babbf9d93c
- Version Independent ID: b51bc104-a6e2-b21f-8362-45cee22e8c22
- Content: Controller action return types in ASP.NET Core Web API
- Content Source: aspnetcore/web-api/action-return-types.md
- Product: aspnet-core
- Technology: aspnetcore-webapi
- GitHub Login: @scottaddie
- Microsoft Alias: scaddie
I had to do the same...
// Act
var createdAtActionResult = await bprsDtFichaVsitaBancaPrvcdController.PostBprsDtFichaVsitaBancaPrvcd(bprsDtFichaVsitaBancaPrvcd);
var item = (BprsDtFichaVsitaBancaPrvcd)((CreatedAtActionResult)createdAtActionResult.Result).Value;
// Assert
Assert.IsType<BprsDtFichaVsitaBancaPrvcd>(item);
Assert.Equal(bprsDtFichaVsitaBancaPrvcd.FecVst, item.FecVst);
I have the same issues that some types can be returned directly like return model.
Some others (like ActionResult<IEnumerable<MyObject>>) have to be wrapped as return Ok(model).
I have not taken a look at it in detail but it seems that there are some issues. As you both wrote before: Because of this you have different tests and the "maybe/maybe not" wrapping it doesn't make it easier.
Moved to Controller action return types container issue #18092
This is being updated for .NET 7. See https://github.com/dotnet/AspNetCore.Docs.Samples/pull/84