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

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

相关推荐
温暖的苹果4 小时前
【.Net runtime】corehost(.NET 应用启动过程)
c#·.net·.netcore
csdn_aspnet5 小时前
使用 Windows 客户端的 RabbitMQ Messaging for .NET 8 Web API 第 2 部分
windows·rabbitmq·.netcore·.net8
csdn_aspnet5 小时前
使用 Windows 客户端的 RabbitMQ Messaging for .NET 8 Web API 第 1 部分
rabbitmq·.net·.netcore·.net8
csdn_aspnet1 天前
ASP.NET Core:创建并验证文档上的数字签名
.netcore·数字签名
喵叔哟5 天前
12.云平台部署
后端·.netcore
爱吃香蕉的阿豪5 天前
NET Core中ConcurrentDictionary详解:并发场景下的安全利器及服务端实践
安全·http·.netcore·高并发
武藤一雄6 天前
彻底吃透.NET中序列化反序列化
xml·微软·c#·json·.net·.netcore
小螺软件宝7 天前
使用DNGuard加密并打包C# .NET Core程序为单一EXE文件
网络·.netcore
武藤一雄8 天前
C#中常见集合都有哪些?
开发语言·微软·c#·.net·.netcore
武藤一雄9 天前
.NET 中常见计时器大全
microsoft·微软·c#·.net·wpf·.netcore