溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何在ASP.NET項目中利用Action返回值類型

發(fā)布時間:2021-01-28 09:36:25 來源:億速云 閱讀:269 作者:Leah 欄目:開發(fā)技術(shù)

今天就跟大家聊聊有關(guān)如何在ASP.NET項目中利用Action返回值類型,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

在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。

如何在ASP.NET項目中利用Action返回值類型

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 。

如何在ASP.NET項目中利用Action返回值類型

但是這看起來顯然不夠優(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。

如何在ASP.NET項目中利用Action返回值類型

解決這個問題就該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)部:

如何在ASP.NET項目中利用Action返回值類型

看到這里就明白了原來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)換的方法

看完上述內(nèi)容,你們對如何在ASP.NET項目中利用Action返回值類型有進一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI