ASP.NET Core Webapi 返回数据的三种方式

ASP.NET Core为Web API控制器方法返回类型提供了如下几个选择:

  • Specific type

  • IActionResult

  • ActionResult<T>

1. 返回指定类型(Specific type)

最简单的API会返回原生的或者复杂的数据类型(比如,string 或者自定义对象类型)。考虑如下的Action方法,其返回了一个自定义的Author对象的集合。

HttpGet

public List<Author> Get() =>

_repository.GetAuthors();

HttpGet

public IEnumerable<Author> Get()

{

return _repository.GetAuthors();

}

从 NetCore 3.0 开始,你不仅可以定义同步形式的 IEnumerable<Author>方法,也可以定义异步形式的 IAsyncEnumerable<T>方法,不同点在于后者是一个异步模式的集合,好处就是不会导致同步迭代,既不阻塞数据库,也不阻塞主线程。

下面的代码展示了如何改造 Get 方法,两个方法返回都是不阻塞的:

HttpGet

public IEnumerable<Author> Get()

{

var authors = _repository.GetAuthors();// 需要等待authors全部查询完成,才会进入下一步迭代,但是返回时又做了一个判断筛选,返回是不阻塞的

foreach (var author in authors) // 适合数据库量大时,只做全部查询,然后通过foreach筛选,yield迭代返回

{

if(author.isMale){

yield return author;

}

}

}

HttpGet

public async IAsyncEnumerable<Author> Get() //异步迭代,既不会阻塞数据库,也不阻塞主线程

{

var authors = GetAuthorsAsync(); // 使用GetAuthorsAsync异步方法,不用authors查询完毕,就会进入下一步迭代返回authors

await foreach (var author in authors)

{

yield return author;

}

}

2. 返回 IActionResult 实例

如果你要返回 data + httpcode 的双重需求,那么 IActionResult 就是你要找的东西,下面的代码片段展示了如何去实现。

HttpGet

public IActionResult Get()

{

if (authors == null)

return NotFound("No records");

return Ok(authors); // 必须有Ok等方法包装

}

上面的代码有 Ok,NotFound 两个方法,对应着 OKResult,NotFoundResult, Http Code 对应着 200,404。当然还有其他的如:CreatedResult, NoContentResult, BadRequestResult, UnauthorizedResult, 和 UnsupportedMediaTypeResult,都是 IActionResult 的子类。

3. 返回 ActionResult<T> 实例

ActionResult<T>包装了前面这种模式:可以返回 IActionResult(data + httpcode),也可以返回指定类型T

HttpGet

public ActionResult<IEnumerable<Author>> Get()

{

if (authors == null)

return NotFound("No records");

return authors;

}

和之前IActionResult的 Get 方法相比,这里如果不需要返回httpCode,则直接返回 authors ,而不需要再用 OK(authors) 包装,是一个非常好的简化,而IActionResult必须要使用Ok等包装一下返回。

接下来再把 Get 方法异步化:

HttpGet

public async Task<ActionResult<IEnumerable<Author>>> Get()

{

var data = await GetAuthors();

if (data == null)

return NotFound("No record");

return data;

}

如果你有一些定制化需求,可以实现一个自定义的 ActionResult 类,做法就是实现 IActionResult 中的 ExecuteResultAsync 方法即可。

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

相关推荐
xingshanchang12 分钟前
Pythonnet - 实现.NET Core和Python进行混合编程
vscode·.netcore
江沉晚呤时1 天前
.NET Core 中 Swagger 配置详解:常用配置与实战技巧
前端·.netcore
矿工学编程1 天前
.NET Core liunx二进制文件安装
.netcore
编程乐趣7 天前
基于.Net Core开发的GraphQL开源项目
后端·.netcore·graphql
吾门7 天前
机器视觉开发教程——C#如何封装海康工业相机SDK调用OpenCV/YOLO/VisionPro/Halcon算法
图像处理·opencv·计算机视觉·c#·.net·.netcore·visual studio
Kookoos9 天前
ABP vNext + EF Core 实战性能调优指南
数据库·后端·c#·.net·.netcore
[email protected]10 天前
ASP.NET Core 中实现 Markdown 渲染中间件
后端·中间件·asp.net·.netcore
吃瓜日常10 天前
ABP项目发布到IIS流程
c#·.netcore
[email protected]12 天前
ASP.NET Core 中间件
后端·中间件·asp.net·.netcore
[email protected]13 天前
ASP.NET Core 请求限速的ActionFilter
后端·asp.net·.netcore