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 方法即可。

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

相关推荐
滴滴答答哒3 天前
.NET Core 基于 AOP + Polly 实现数据库死锁自动重试
数据库·.netcore·sqlsugar
.NET修仙日记7 天前
.NET EFCore批量插入性能优化实战:30秒 → 0.5秒
性能优化·c#·.net·.netcore·微软技术·efcore·踩坑实录
Kimhill张10 天前
.net core8 WPF 依赖注入(DI)
wpf·.netcore
wangl_9211 天前
C# / .NET 在工业环境中的优势
开发语言·c#·.net·.netcore·.net core·visual studio
豆豆14 天前
信创环境下CMS国产化适配实践:以.NET Core路线为例的技术验证
.netcore·cms·信创·国产化·建站系统·内容管理系统·网站管理系统
时光追逐者14 天前
C#/.NET/.NET Core技术前沿周刊 | 第 70 期(2026年5.01-5.10)
c#·.net·.netcore
van久18 天前
Day20:AutoMapper 对象映射
.netcore
van久19 天前
Day23 登录 + 颁发 Token(DDD 四层架构 + 企业标准)
.netcore
wangl_9220 天前
C#性能优化完全指南 - 从原理到实践
开发语言·性能优化·c#·.net·.netcore·visual studio
宝桥南山23 天前
GitHub Models - 尝试一下使用GitHub Models
microsoft·ai·微软·c#·github·.netcore