问题
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?
回答1:
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.
回答2:
You can return - Specific Type - IActionResult - ActionResult
For more details, please refer MSDN article at : https://docs.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-2.2
来源:https://stackoverflow.com/questions/53987450/correct-return-type-from-web-api