正确的Web API返回类型 [英] Correct return type from web API

查看:111
本文介绍了正确的Web API返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的下一个项目创建一个c#.net core 2.2 Web API.我的问题是何时返回数据时应该返回对象还是IActionResult OK(returnObject)?

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)?

我问的原因是我正在使用swagger和swagger studio为Angular前端创建模型.如果我从API返回了IActionResult,则返回的视图模型在swagger.json文件中没有详细说明,因此我必须在angular应用程序中对它们进行编码.如果返回创建的任何对象,则会在swagger.json中创建模型.

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.

在这种情况下,我应该遵循哪种做法从API返回数据?

What practice should I follow to return data from an API in this case?

推荐答案

您确实想返回IActionResult(object),但还没有完成.

You do want to return IActionResult(object) but you are not quite done.

ProducesAttribute注释控制器,并用ProducesResponseTypeAttribute注释方法:

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)
    { ... }
}

这使Swagger UI知道期望什么并适当记录它.上面显示的是同步方法;它也适用于异步.

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.

这篇关于正确的Web API返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆