.net mvc actionresult 返回字符串_ASP.NET Core中的Action的返回值类型
在Asp.net Core之前所有的Action返回值都是ActionResult,Json(),File()等方法返回的都是ActionResult的子類。并且Core把MVC跟WebApi合并之后Action的返回值體系也有了很大的變化。
ActionResult類
ActionResult類是最常用的返回值類型。基本沿用了之前Asp.net MVC的那套東西,使用它大部分情況都沒(méi)問(wèn)題。比如用它來(lái)返回視圖,返回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類實(shí)現(xiàn)了IActionResult接口所以能用ActionResult的地方都可以使用IActionResult來(lái)替換。同樣異步的話使用Task包起來(lái)做為返回值。
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 AsyncCall() { await Task.Delay(1000); return Content("ok"); } }直接返回POCO類
Asp.net Core的Controller的Action可以把POCO類型(其實(shí)不一定是POCO類,可以是任意類型,但是使用的時(shí)候一般都返回viwemodel等POCO類)當(dāng)做返回值,不一定非要是ActionResult或者IActionResult。Asp.net Core框架會(huì)幫我們自動(dòng)序列化返回給前端,默認(rèn)使用json序列化。同樣異步的話使用Task包起來(lái)做為返回值。
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> GetPersons() { await Task.Delay(1000); return new List { new Person { Name = "abc", Sex = "f" }, new Person { Name = "efg", Sex = "m" } }; } }ActionResult< T >泛型類
當(dāng)我們?cè)O(shè)計(jì)restful webapi系統(tǒng)的時(shí)候習(xí)慣使用POCO作為返回值。比如我們?cè)O(shè)計(jì)一個(gè)獲取Person的api。通過(guò) /person/001 url獲取001號(hào)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); } }這個(gè)方法看起來(lái)好像沒(méi)什么問(wèn)題,但其實(shí)有個(gè)小問(wèn)題。如果repository.Get方法沒(méi)有根據(jù)id查找到數(shù)據(jù),那么將會(huì)返回null。如果null做為Action的返回值,最后框架會(huì)轉(zhuǎn)換為204的http status code。
204表示No Content 。做為restful api,204的語(yǔ)義在這里會(huì)有問(wèn)題,這里比較適合的status code是404 NOT FOUND 。那么我們來(lái)改一下:
[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)會(huì)返回404 Not Found 。
但是這看起來(lái)顯然不夠優(yōu)雅,因?yàn)镃ontrollerBase內(nèi)置了NotFoundResult NotFound() 方法。這使用這個(gè)方法代碼看起來(lái)更加清晰明了。繼續(xù)改:
[HttpGet("{id}")] public Person Get(string id) { var person = _repository.Get(id); if (person == null) { return NotFound(); } return person; }很不幸,這段代碼VS會(huì)提示錯(cuò)誤。因?yàn)榉祷刂殿愋筒灰恢隆7椒ê灻姆祷刂凳荘erson,但是方法內(nèi)部一會(huì)返回NotFoundResult,一會(huì)返回Person。
解決這個(gè)問(wèn)題就該ActionResult< T >出場(chǎng)了。我們繼續(xù)改一下:
[HttpGet("{id}")] public ActionResult Get(string id) { var person = _repository.Get(id); if (person == null) { return NotFound(); } return person; }現(xiàn)在VS已經(jīng)不會(huì)報(bào)錯(cuò)了,運(yùn)行一下也可以正常工作。但仔細(xì)想想也很奇怪,為什么返回值類型改成了ActionResult< Person >就不報(bào)錯(cuò)了呢?明明返回值類型跟方法簽名還是不一致啊?
深入ActionResult< T >
接上面的問(wèn)題,讓我們看一下ActionResult的內(nèi)部:
看到這里就明白了原來(lái)ActionResult< T >里面內(nèi)置了2個(gè)implicit operator方法。implicit operator用于聲明隱式類型轉(zhuǎn)換。
public static implicit operator ActionResult(ActionResult result);表示ActionResult類型可以轉(zhuǎn)換為ActionResult< TValue >類型。
public static implicit operator ActionResult(TValue value)表示TValue類型可以轉(zhuǎn)換為ActionResult< TValue >類型。
因?yàn)橛辛诉@2個(gè)方法,當(dāng)ActionResult或者TValue類型往ActionResult< T >賦值的時(shí)候會(huì)進(jìn)行一次自動(dòng)的類型轉(zhuǎn)換。所以VS這里不會(huì)報(bào)錯(cuò)。
總結(jié)
總結(jié)
以上是生活随笔為你收集整理的.net mvc actionresult 返回字符串_ASP.NET Core中的Action的返回值类型的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 股票双头还是单头好?
- 下一篇: php asp.net 代码量少,.NE