Reputation: 103
I am creating a c# .net core 2.2 web API for my next project. My question is when returning data should I return the object or IActionResult OK(returnObject)
?
The reason I ask is I am using swagger and swagger studio to create my models for an Angular front end. If I return an IActionResult
from the API the returned view models are not detailed in the swagger.json
file so I would have to code these in the angular application. If I return whatever object is created the model is created in the swagger.json
.
What practice should I follow to return data from an API in this case?
Upvotes: 5
Views: 5987
Reputation: 5634
You can return - Specific Type - IActionResult - ActionResult
For more details, please refer MSDN article at : https://learn.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-2.2
Upvotes: 1
Reputation: 21709
You do want to return IActionResult(object)
but you are not quite done.
Annotate your controller with the ProducesAttribute
and annotate your method with the ProducesResponseTypeAttribute
:
[Produces("application/json")]
public class SomethingController
{
[ProducesResponseType(typeof(YourObject), (int)HttpStatusCode.OK)]
public IActionResult GetThing(int id)
{ ... }
}
This allows Swagger UI to know what to expect and document it appropriately. Shown above is for a synchronous method; it works for asynchronous as well.
Upvotes: 12