詳解如何在ASP.NET Core Web API中以三種方式返回?cái)?shù)據(jù)
在 ASP.NET Core 中有三種返回 數(shù)據(jù) 和 HTTP狀態(tài)碼 的方式,最簡單的就是直接返回指定的類型實(shí)例,如下代碼所示:
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
除了這種,也可以返回 IActionResult 實(shí)例 和 ActionResult <T> 實(shí)例。
雖然返回指定的類型 是最簡單粗暴的,但它只能返回?cái)?shù)據(jù),附帶不了http狀態(tài)碼,而 IActionResult 實(shí)例可以將 數(shù)據(jù) + Http狀態(tài)碼 一同帶給前端,最后就是 ActionResult<T> 它封裝了前面兩者,可以實(shí)現(xiàn)兩種模式的自由切換,🐂吧。
接下來一起討論下如何在 ASP.NET Core Web API 中使用這三種方式。
創(chuàng)建 Controller 和 Model 類
在項(xiàng)目的 Models 文件夾下新建一個(gè) Author 類,代碼如下:
public class Author
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
有了這個(gè) Author 類,接下來創(chuàng)建一個(gè) DefaultController 類。
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace IDGCoreWebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class DefaultController : ControllerBase
{
private readonly List<Author> authors = new List<Author>();
public DefaultController()
{
authors.Add(new Author()
{
Id = 1,
FirstName = "Joydip",
LastName = "Kanjilal"
});
authors.Add(new Author()
{
Id = 2,
FirstName = "Steve",
LastName = "Smith"
});
}
[HttpGet]
public IEnumerable<Author> Get()
{
return authors;
}
[HttpGet("{id}", Name = "Get")]
public Author Get(int id)
{
return authors.Find(x => x.Id == id);
}
}
}
在 Action 中返回 指定類型
最簡單的方式就是在 Action 中直接返回一個(gè) 簡單類型 或者 復(fù)雜類型,其實(shí)在上面的代碼清單中,可以看到 Get 方法返回了一個(gè) authors 集合,看清楚了,這個(gè)方法定義的是 IEnumerable<Author>。
[HttpGet]
public IEnumerable<Author> Get()
{
return authors;
}
在 ASP.NET Core 3.0 開始,你不僅可以定義同步形式的 IEnumerable<Author>方法,也可以定義異步形式的 IAsyncEnumerable<T>方法,后者的不同點(diǎn)在于它是一個(gè)異步模式的集合,好處就是 不阻塞 當(dāng)前的調(diào)用線程,關(guān)于 IAsyncEnumerable<T> 更多的知識(shí),我會(huì)在后面的文章中和大家分享。
下面的代碼展示了如何用 異步集合 來改造 Get 方法。
[HttpGet]
public async IAsyncEnumerable<Author> Get()
{
var authors = await GetAuthors();
await foreach (var author in authors)
{
yield return author;
}
}
在 Action 中返回 IActionResult 實(shí)例
如果你要返回 data + httpcode 的雙重需求,那么 IActionResult 就是你要找的東西,下面的代碼片段展示了如何去實(shí)現(xiàn)。
[HttpGet]
public IActionResult Get()
{
if (authors == null)
return NotFound("No records");
return Ok(authors);
}
上面的代碼有 Ok,NotFound 兩個(gè)方法,對(duì)應(yīng)著 OKResult,NotFoundResult, Http Code 對(duì)應(yīng)著 200,404。當(dāng)然還有其他的如:CreatedResult, NoContentResult, BadRequestResult, UnauthorizedResult, 和 UnsupportedMediaTypeResult,都是 IActionResult 的子類。
在 Action 中返回 ActionResult<T> 實(shí)例
ActionResult<T> 是在 ASP.NET Core 2.1 中被引入的,它的作用就是包裝了前面這種模式,怎么理解呢? 就是即可以返回 IActionResult ,也可以返回指定類型,從 ActionResult<TValue> 類下的兩個(gè)構(gòu)造函數(shù)中就可以看的出來。
public sealed class ActionResult<TValue> : IConvertToActionResult
{
public ActionResult Result {get;}
public TValue Value {get;}
public ActionResult(TValue value)
{
if (typeof(IActionResult).IsAssignableFrom(typeof(TValue)))
{
throw new ArgumentException(Resources.FormatInvalidTypeTForActionResultOfT(typeof(TValue), "ActionResult<T>"));
}
Value = value;
}
public ActionResult(ActionResult result)
{
if (typeof(IActionResult).IsAssignableFrom(typeof(TValue)))
{
throw new ArgumentException(Resources.FormatInvalidTypeTForActionResultOfT(typeof(TValue), "ActionResult<T>"));
}
Result = (result ?? throw new ArgumentNullException("result"));
}
}
有了這個(gè)基礎(chǔ),接下來看看如何在 Action 方法中去接這兩種類型。
[HttpGet]
public ActionResult<IEnumerable<Author>> Get()
{
if (authors == null)
return NotFound("No records");
return authors;
}
和文章之前的 Get 方法相比,這里直接返回 authors 而不需要再用 OK(authors) 包裝,是不是一個(gè)非常好的簡化呢? 接下來再把 Get 方法異步化,首先考慮下面返回 authors 集合的異步方法。
private async Task<List<Author>> GetAuthors()
{
await Task.Delay(100).ConfigureAwait(false);
return authors;
}
值得注意的是,異步方法必須要有至少一個(gè) await 語句,如果不這樣做的話,編譯器會(huì)提示一個(gè)警告錯(cuò)誤,告知你這個(gè)方法將會(huì)被 同步執(zhí)行,為了避免出現(xiàn)這種尷尬,我在 Task.Delay 上做了一個(gè) await。
下面就是更新后的 Get 方法,注意一下這里我用了 await 去調(diào)用剛才創(chuàng)建的異步方法,代碼參考如下。
[HttpGet]
public async Task<ActionResult<IEnumerable<Author>>> Get()
{
var data = await GetAuthors();
if (data == null)
return NotFound("No record");
return data;
}
如果你有一些定制化需求,可以實(shí)現(xiàn)一個(gè)自定義的 ActionResult 類,做法就是實(shí)現(xiàn) IActionResult 中的 ExecuteResultAsync 方法即可。
譯文鏈接:https://www.infoworld.com/article/3520770/how-to-return-data-from-aspnet-core-web-api.html
到此這篇關(guān)于詳解如何在ASP.NET Core Web API中以三種方式返回?cái)?shù)據(jù)的文章就介紹到這了,更多相關(guān)ASP.NET Core Web API返回?cái)?shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- ASP.NET Core3.1 Ocelot負(fù)載均衡的實(shí)現(xiàn)
- ASP.NET Core3.1 Ocelot認(rèn)證的實(shí)現(xiàn)
- ASP.NET Core3.1 Ocelot路由的實(shí)現(xiàn)
- Asp.Net Core 調(diào)用第三方Open API查詢物流數(shù)據(jù)的示例
- ASP.NET Core WebApi版本控制的實(shí)現(xiàn)
- asp.net core webapi文件上傳功能的實(shí)現(xiàn)
- 詳解ASP.NET Core Web Api之JWT刷新Token
- 在IIS上部署ASP.NET Core Web API的方法步驟
- ASP.NET Core WebAPI實(shí)現(xiàn)本地化(單資源文件)
- ASP.NET Core3.x API版本控制的實(shí)現(xiàn)
- Asp.Net Core使用swagger生成api文檔的完整步驟
- ASP.NET Core Api網(wǎng)關(guān)Ocelot的使用初探
相關(guān)文章
WEB在模態(tài)窗體里導(dǎo)出或下載文件功能代碼
實(shí)現(xiàn)在模態(tài)窗體里導(dǎo)出或下載文件,具體功能代碼如下,感興趣的朋友可以參考下哈2013-06-06
asp.net使用FCK編輯器中的分頁符實(shí)現(xiàn)長文章分頁功能
這篇文章主要介紹了asp.net使用FCK編輯器中的分頁符實(shí)現(xiàn)長文章分頁功能,涉及asp.net字符串及分頁操作的相關(guān)技巧,需要的朋友可以參考下2016-06-06
使用ASP.NET MVC引擎開發(fā)插件系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了使用ASP.NET MVC引擎開發(fā)插件系統(tǒng)的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05
.NET CORE3.1實(shí)現(xiàn)微信小程序發(fā)送訂閱消息
這篇文章主要介紹了.NET CORE3.1實(shí)現(xiàn)微信小程序發(fā)送訂閱消息,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
.net MVC使用Session驗(yàn)證用戶登錄(4)
這篇文章主要為大家詳細(xì)介紹了.net MVC使用Session驗(yàn)證用戶登錄的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-04-04
ASP.NET Core Web中使用AutoMapper進(jìn)行對(duì)象映射
AutoMapper是一個(gè)簡單易用的.NET對(duì)象映射庫,用于快速、方便地進(jìn)行對(duì)象之間的轉(zhuǎn)換和映射,極大的簡化了開發(fā)人員在處理對(duì)象映射時(shí)的工作量,今天我們來講講在ASP.NET Core Web中使用AutoMapper快速進(jìn)行對(duì)象映射,感興趣的朋友跟隨小編一起看看吧2024-05-05

