ASP.NET Core中的Action的返回值類型實現(xiàn)
在Asp.net Core之前所有的Action返回值都是ActionResult,Json(),File()等方法返回的都是ActionResult的子類。并且Core把MVC跟WebApi合并之后Action的返回值體系也有了很大的變化。
ActionResult類
ActionResult類是最常用的返回值類型?;狙赜昧酥癆sp.net MVC的那套東西,使用它大部分情況都沒問題。比如用它來返回視圖,返回json,返回文件等等。如果是異步則使用Task
public class TestController : Controller { public ActionResult Index() { return View(); } public ActionResult MyFile() { return File(new byte[] { }, "image/jpg"); } public ActionResult MyJson() { return Json(new { name = "json" }); } public ActionResult Ok() { return Ok(); } }
IActionResult接口
ActionResult類實現(xiàn)了IActionResult接口所以能用ActionResult的地方都可以使用IActionResult來替換。同樣異步的話使用Task包起來做為返回值。
public class ITestController : Controller { public IActionResult Index() { return View(); } public IActionResult MyFile() { return File(new byte[] { }, "image/jpg"); } public IActionResult MyJson() { return Json(new { name = "json" }); } public IActionResult HttpOk() { return Ok(); } public async Task<IActionResult> AsyncCall() { await Task.Delay(1000); return Content("ok"); } }
直接返回POCO類
Asp.net Core的Controller的Action可以把POCO類型(其實不一定是POCO類,可以是任意類型,但是使用的時候一般都返回viwemodel等POCO類)當(dāng)做返回值,不一定非要是ActionResult或者IActionResult。Asp.net Core框架會幫我們自動序列化返回給前端,默認使用json序列化。同樣異步的話使用Task包起來做為返回值。
public class Person { public string Name { get; set; } public string Sex { get; set; } } public class ITestController : Controller { public Person GetPerson() { return new Person { Name = "abc", Sex = "f" }; } public async Task<List<Person>> GetPersons() { await Task.Delay(1000); return new List<Person> { new Person { Name = "abc", Sex = "f" }, new Person { Name = "efg", Sex = "m" } }; } }
ActionResult< T >泛型類
當(dāng)我們設(shè)計restful webapi系統(tǒng)的時候習(xí)慣使用POCO做為返回值。比如我們設(shè)計一個獲取Person的api。通過 /person/001 url獲取001號person。
[Route("[controller]")] public class PersonController : Controller { IPersonRepository _repository; PersonController(IPersonRepository repository) { _repository = repository; } [HttpGet("{id}")] public Person Get(string id) { return _repository.Get(id); } }
這個方法看起來好像沒什么問題,但其實有個小問題。如果repository.Get方法沒有根據(jù)id查找到數(shù)據(jù),那么將會返回null。如果null做為Action的返回值,最后框架會轉(zhuǎn)換為204的http status code。
204表示No Content 。做為restful api,204的語義在這里會有問題,這里比較適合的status code是404 NOT FOUND 。那么我們來改一下:
[HttpGet("{id}")] public Person Get(string id) { var person = _repository.Get(id); if (person == null) { Response.StatusCode = 404; } return person; }
現(xiàn)在如果查找不到person數(shù)據(jù),則系統(tǒng)會返回404 Not Found 。
但是這看起來顯然不夠優(yōu)雅,因為ControllerBase內(nèi)置了NotFoundResult NotFound() 方法。這使用這個方法代碼看起來更加清晰明了。繼續(xù)改:
[HttpGet("{id}")] public Person Get(string id) { var person = _repository.Get(id); if (person == null) { return NotFound(); } return person; }
很不幸,這段代碼VS會提示錯誤。因為返回值類型不一致。方法簽名的返回值是Person,但是方法內(nèi)部一會返回NotFoundResult,一會返回Person。
解決這個問題就該ActionResult< T >出場了。我們繼續(xù)改一下:
[HttpGet("{id}")] public ActionResult<Person> Get(string id) { var person = _repository.Get(id); if (person == null) { return NotFound(); } return person; }
現(xiàn)在VS已經(jīng)不會報錯了,運行一下也可以正常工作。但仔細想想也很奇怪,為什么返回值類型改成了ActionResult< Person >就不報錯了呢?明明返回值類型跟方法簽名還是不一致?。?/p>
深入ActionResult< T >
接上面的問題,讓我們看一下ActionResult的內(nèi)部:
看到這里就明白了原來ActionResult< T >里面內(nèi)置了2個implicit operator方法。implicit operator用于聲明隱式類型轉(zhuǎn)換。
public static implicit operator ActionResult<TValue>(ActionResult result);
表示ActionResult類型可以轉(zhuǎn)換為ActionResult< TValue >類型。
public static implicit operator ActionResult<TValue>(TValue value)
表示TValue類型可以轉(zhuǎn)換為ActionResult< TValue >類型。
因為有了這2個方法,當(dāng)ActionResult或者TValue類型往ActionResult< T >賦值的時候會進行一次自動的類型轉(zhuǎn)換。所以VS這里不會報錯。
總結(jié)
- 大部分時候Action的返回值可以使用ActionResult/IActionResult
- 設(shè)計restful api的時候可以直接使用POCO類作為返回值
- 如果要設(shè)計既支持POCO類返回值或者ActionResult類為返回值的action可以使用ActionResult< T >作為返回值
- ActionResult< T >之所以能夠支持兩種類型的返回值類型,是因為使用了implicit operator內(nèi)置了2個隱式轉(zhuǎn)換的方法
到此這篇關(guān)于ASP.NET Core中的Action的返回值類型實現(xiàn)的文章就介紹到這了,更多相關(guān)ASP.NET Core Action的返回值類型內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SignalR Self Host+MVC等多端消息推送服務(wù)(二)
這篇文章主要為大家詳細介紹了SignalR Self Host+MVC等多端消息推送服務(wù)的第二篇,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06javascript實現(xiàn)listbox左右移動實現(xiàn)代碼
javascript實現(xiàn)listbox左右移動實現(xiàn)代碼,需要的朋友可以參考下。2010-05-05Community Server專題二:體系結(jié)構(gòu)
Community Server專題二:體系結(jié)構(gòu)...2007-03-03ASP.Net MVC+Data Table實現(xiàn)分頁+排序功能的方法
這篇文章主要介紹了ASP.Net MVC+Data Table實現(xiàn)分頁+排序功能的方法,結(jié)合實例形式分析了asp.net基于mvc架構(gòu)實現(xiàn)的數(shù)據(jù)查詢、排序、分頁顯示等相關(guān)操作技巧,需要的朋友可以參考下2017-06-06關(guān)于asp.net button按鈕的OnClick和OnClientClick事件
OnClick是button的服務(wù)器端事件 OnClientClick是button的客戶端事件2009-05-05