詳解如何在ASP.NET Core Web API中以三種方式返回數(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í)例。
雖然返回指定的類型 是最簡單粗暴的,但它只能返回數(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 文件夾下新建一個 Author 類,代碼如下:
public class Author { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } }
有了這個 Author 類,接下來創(chuàng)建一個 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 中直接返回一個 簡單類型 或者 復(fù)雜類型,其實(shí)在上面的代碼清單中,可以看到 Get 方法返回了一個 authors 集合,看清楚了,這個方法定義的是 IEnumerable<Author>。
[HttpGet] public IEnumerable<Author> Get() { return authors; }
在 ASP.NET Core 3.0 開始,你不僅可以定義同步形式的 IEnumerable<Author>方法,也可以定義異步形式的 IAsyncEnumerable<T>方法,后者的不同點(diǎn)在于它是一個異步模式的集合,好處就是 不阻塞 當(dāng)前的調(diào)用線程,關(guān)于 IAsyncEnumerable<T> 更多的知識,我會在后面的文章中和大家分享。
下面的代碼展示了如何用 異步集合 來改造 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 兩個方法,對應(yīng)著 OKResult,NotFoundResult, Http Code 對應(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ò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")); } }
有了這個基礎(chǔ),接下來看看如何在 Action 方法中去接這兩種類型。
[HttpGet] public ActionResult<IEnumerable<Author>> Get() { if (authors == null) return NotFound("No records"); return authors; }
和文章之前的 Get 方法相比,這里直接返回 authors 而不需要再用 OK(authors) 包裝,是不是一個非常好的簡化呢? 接下來再把 Get 方法異步化,首先考慮下面返回 authors 集合的異步方法。
private async Task<List<Author>> GetAuthors() { await Task.Delay(100).ConfigureAwait(false); return authors; }
值得注意的是,異步方法必須要有至少一個 await 語句,如果不這樣做的話,編譯器會提示一個警告錯誤,告知你這個方法將會被 同步執(zhí)行,為了避免出現(xiàn)這種尷尬,我在 Task.Delay 上做了一個 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)一個自定義的 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中以三種方式返回數(shù)據(jù)的文章就介紹到這了,更多相關(guān)ASP.NET Core Web API返回數(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)文章
剖析Asp.Net Web API路由系統(tǒng)---WebHost部署方式
這篇文章主要介紹了剖析Asp.Net Web API路由系統(tǒng)---WebHost部署方式,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-02-02關(guān)于利用RabbitMQ實(shí)現(xiàn)延遲任務(wù)的方法詳解
最近在使用RabbitMQ來實(shí)現(xiàn)延遲任務(wù)的時候發(fā)現(xiàn),這其中的知識點(diǎn)還是挺多的,所以下面這篇文章主要給大家介紹了關(guān)于利用RabbitMQ實(shí)現(xiàn)延遲任務(wù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下。2017-12-12.Net基于MVC4 Web Api輸出Json格式實(shí)例
這篇文章主要介紹了.Net基于MVC4 Web Api輸出Json格式的實(shí)現(xiàn)方法,實(shí)例講述了Global中json的操作與XML的處理等技巧,需要的朋友可以參考下2014-10-10asp.net使用jQuery獲取RadioButtonList成員選中內(nèi)容和值示例
這篇文章主要介紹了通過jQuery來獲取RadioButtonList成員內(nèi)容的方法,大家參考使用吧2014-01-01.Net學(xué)習(xí)筆記之Layui多圖片上傳功能
這篇文章主要給大家介紹了關(guān)于.Net學(xué)習(xí)筆記之Layui多圖片上傳功能的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用.Net具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07