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

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

相关推荐
1-1=017 小时前
.NET 实现后台任务
c#·.net·.netcore·quartz·hangfire
FuckPatience18 小时前
Windows 窗体设计器不支持项目“xxx,因为它面向不受支持的.NET Core 3.1。建议更新到受支持的.NET 版本。
.netcore
csdn_aspnet2 天前
C# .NetCore Swagger ISchemaFilter 处理枚举、特殊类型
c#·.netcore·swagger
code_long3 天前
.net core 连接打印机 使用zpl指令打印机,并且位图本地渲染zpl指令
c#·.netcore·位图·打印机·模板编辑·模板预览
csdn_aspnet3 天前
C# .NetCore Swagger ISchemaFilter Long 转 String 防精度丢失
c#·.netcore·swagger
csdn_aspnet4 天前
C# .NetCore Swagger ISchemaFilter 注入示例值、描述
c#·.netcore·swagger
宝桥南山6 天前
.NET 11 - 尝试一下Minimal API中的异步验证新特性
microsoft·微软·c#·asp.net·.net·.netcore
上位机妹子10 天前
EF Core 两种继承映射:每层次一张表(TPH)与每类型一张表(TPT)
数据库·c#·.netcore·ef core
csdn_aspnet1 个月前
.NetCore Webapi 接口验证请求来源
.netcore·ip·token·签名·webapi·cors·sign
宝桥南山1 个月前
Microsoft Fabric - 简单尝试一下Microsoft Fabric .NET SDK
microsoft·微软·.net·.netcore·powerbi·fabric