ASP.NET Core Web API 控制器與方法返回輸出


DATA ACCESS LAYER

在一些不同的示例教程中,我們可能看到 DAL 的實現在主項目中,並且每個控制器中都有實例。我們不建議這么做。

當我們編寫 DAL 時,我們應該將其作為一個獨立的服務來創建。在 .NET Core 項目中,這一點很重要,因為當我們將 DAL 作為一個獨立的服務時,我們就可以將其直接注入到 IOC(控制反轉)容器中。IOC 是 .NET Core 內置功能。通過這種方式,我們可以在任何控制器中通過構造函數注入的方式來使用。

 

public class OwnerController: Controller
{
   private IRepository _repository;
   public OwnerController(IRepository repository)
   {
       _repository = repository;
   }
}

  

CONTROLLERS

控制器應該始終盡量保持整潔。我們不應該將任何業務邏輯放置於內。

因此,我們的控制器應該通過構造函數注入的方式接收服務實例,並組織 HTTP 的操作方法(GET,POST,PUT,DELETE,PATCH...):

 

public class OwnerController : Controller
{
   private readonly ILoggerManager _logger;
   private readonly IRepository _repository;
   public OwnerController(ILoggerManager logger, IRepository repository)
   {
       _logger = logger;
       _repository = repository;
   }

   [HttpGet]
   public IActionResult GetAllOwners()
   {
   }
   [HttpGet("{id}", Name = "OwnerById")]
   public IActionResult GetOwnerById(Guid id)
   {
   }
   [HttpGet("{id}/account")]
   public IActionResult GetOwnerWithDetails(Guid id)
   {
   }
   [HttpPost]
   public IActionResult CreateOwner([FromBody]Owner owner)
   {
   }
   [HttpPut("{id}")]
   public IActionResult UpdateOwner(Guid id, [FromBody]Owner owner)
   {
   }
   [HttpDelete("{id}")]
   public IActionResult DeleteOwner(Guid id)
   {
   }
}

 

  

我們的 Action 應該盡量保持簡潔,它們的職責應該包括處理 HTTP 請求,驗證模型,捕捉異常和返回響應。

[HttpPost]
public IActionResult CreateOwner([FromBody]Owner owner)
{
   try
   {
       if (owner.IsObjectNull())
       {
           return BadRequest("Owner object is null");
       }
       if (!ModelState.IsValid)
       {
           return BadRequest("Invalid model object");
       }
       _repository.Owner.CreateOwner(owner);
       return CreatedAtRoute("OwnerById", new { id = owner.Id }, owner);
   }
   catch (Exception ex)
   {
       _logger.LogError($"Something went wrong inside the CreateOwner action: { ex} ");
       return StatusCode(500, "Internal server error");
   }
}

 

  

在大多數情況下,我們的 action 應該將 IActonResult 作為返回類型(有時我們希望返回一個特定類型或者是 JsonResult ...)。通過使用這種方式,我們可以很好地使用 .NET Core 中內置方法的返回值和狀態碼。

使用最多的方法是:

    • OK => returns the 200 status code

    • NotFound => returns the 404 status code

    • BadRequest => returns the 400 status code

    • NoContent => returns the 204 status code

    • Created, CreatedAtRoute, CreatedAtAction => returns the 201 status code

    • Unauthorized => returns the 401 status code

    • Forbid => returns the 403 status code

    • StatusCode => returns the status code we provide as input


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM