ASP.NET Core中的Action的返回值型別
在Asp.net Core之前所有的Action返回值都是ActionResult,Json(),File()等方法返回的都是ActionResult的子類。並且Core把MVC跟WebApi合併之後Action的返回值體系也有了很大的變化。
ActionResult類
ActionResult類是最常用的返回值型別。基本沿用了之前Asp.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類實現了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類)當做返回值,不一定非要是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 >泛型類
當我們設計restful webapi系統的時候習慣使用POCO做為返回值。比如我們設計一個獲取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方法沒有根據id查詢到資料,那麼將會返回null。如果null做為Action的返回值,最後框架會轉換為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;
}
現在如果查詢不到person資料,則系統會返回404 Not Found 。
但是這看起來顯然不夠優雅,因為ControllerBase內建了NotFoundResult NotFound() 方法。這使用這個方法程式碼看起來更加清晰明瞭。繼續改:
[HttpGet("{id}")]
public Person Get(string id)
{
var person = _repository.Get(id);
if (person == null)
{
return NotFound();
}
return person;
}
很不幸,這段程式碼VS會提示錯誤。因為返回值型別不一致。方法簽名的返回值是Person,但是方法內部一會返回NotFoundResult,一會返回Person。
解決這個問題就該ActionResult< T >出場了。我們繼續改一下:
[HttpGet("{id}")]
public ActionResult<Person> Get(string id)
{
var person = _repository.Get(id);
if (person == null)
{
return NotFound();
}
return person;
}
現在VS已經不會報錯了,執行一下也可以正常工作。但仔細想想也很奇怪,為什麼返回值型別改成了ActionResult< Person >就不報錯了呢?明明返回值型別跟方法簽名還是不一致啊?
深入ActionResult< T >
接上面的問題,讓我們看一下ActionResult的內部:
看到這裡就明白了原來ActionResult< T >裡面內建了2個implicit operator方法。implicit operator用於宣告隱式型別轉換。
public static implicit operator ActionResult<TValue>(ActionResult result);
表示ActionResult型別可以轉換為ActionResult< TValue >型別。
public static implicit operator ActionResult<TValue>(TValue value)
表示TValue型別可以轉換為ActionResult< TValue >型別。
因為有了這2個方法,當ActionResult或者TValue型別往ActionResult< T >賦值的時候會進行一次自動的型別轉換。所以VS這裡不會報錯。
總結
- 大部分時候Action的返回值可以使用ActionResult/IActionResult
- 設計restful api的時候可以直接使用POCO類作為返回值
- 如果要設計既支援POCO類返回值或者ActionResult類為返回值的action可以使用ActionResult< T >作為返回值
- ActionResult< T >之所以能夠支援兩種型別的返回值型別,是因為使用了implicit operator內建了2個隱式轉換的方法