Netcore 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 async IAsyncEnumerable<Author> Get()
{
 var authors = await GetAuthors();
 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,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 方法相比,这里直接返回authors而不需要再用OK(authors)包装,是一个非常好的简化。

接下来再把 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 方法即可。

以上就是Netcore Webapi返回数据的三种方式示例的详细内容,更多关于Netcore Webapi 返回数据的资料请关注编程宝库其它相关文章!

 一:Hashtable 类简单说明1)表示根据键的哈希代码进行组织的键/值对的集合。使用哈希代码生成的哈希值,是唯一地标识数据的固定长度的数字值。2)HashTable是System.Co ...