Correct return type from web API

馋奶兔 提交于 2019-12-24 01:09:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!