ASP.NET Core Web API 控制器
- 4 分鐘
在上一個練習中,您建立了一個 Web 應用程式來提供範例天氣預報資料,然後在 HTTP「讀取、求值、輸出」迴圈 (REPL) 中與其互動。
在您開始撰寫自己的 PizzaController 類別之前,讓我們先看看 WeatherController 範例中的程式碼,以了解其運作方式。 在本單元中,您將了解 WeatherController 如何使用 ControllerBase 基底類別和一些 .NET 屬性,在十幾行的程式碼中建置功能性 Web API。 了解那些概念之後,您就可以開始撰寫自己的 PizzaController 類別。
以下是整個 WeatherController 類別的程式碼。 如果其還不合理,別擔心。 讓我們逐步完成。
using Microsoft.AspNetCore.Mvc;
namespace ContosoPizza.Controllers;
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
基底類別:ControllerBase
控制器是一個公用類別,其中具有一或多個稱為「動作」的公用方法。 依照慣例,控制器會放在專案根目錄的 Controllers 目錄中。 動作會透過路由公開為 HTTP 端點。 因此,對 https://localhost:{PORT}/weatherforecast 的 HTTP GET 要求會導致 WeatherForecastController 類別的 Get() 方法執行。
首先要注意的事是,此類別繼承自 ControllerBase 基底類別。 此基底類別提供許多標準功能來處理 HTTP 要求,讓您能夠專注於應用程式的特定商務邏輯。
注意
如果您在 ASP.NET Core 中有 Razor Pages 或 Model-View-Controller (MVC) 架構開發的體驗,就曾用過 Controller 類別。 不要透過從 Controller 類別衍生的方式來建立 Web API 控制器。 Controller 衍生自 ControllerBase,並新增對檢視的支援,因此其會用於處理網頁,而非 Web API 要求。
API 控制器類別屬性
有兩個重要屬性會套用至 WeatherForecastController,如下列程式碼所示:
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
[ApiController] 會啟用固定的行為,以使建置 Web API 變得更容易。 某些行為包括 參數來源推斷、 屬性路由作為需求,以及 模型驗證錯誤處理增強功能*。
[Route] 會定義路由模式 [controller]。 控制器的名稱(不區分大小寫,且不含 控制器 後綴)將取代[controller]佔位符。 此控制器會處理對 https://localhost:{PORT}/weatherforecast 的要求。
注意
路由可能包含靜態字串,如 api/[controller] 中所示。 在此範例中,此控制器會處理對 https://localhost:{PORT}/api/weatherforecast 的要求。
使用 Get() 方法提供天氣結果
WeatherForecastController 包含單一控制器動作,由 [HttpGet(Name = "GetWeatherForecast")] 屬性指定。 此屬性會將 HTTP GET 要求路由傳送至 public IEnumerable<WeatherForecast> Get() 方法。 如您在上一個練習中所見,對 https://localhost:{PORT}/weatherforecast 的要求已導致傳回天氣結果。
如您稍後將在此課程模組中了解的,其他常見動作會與執行 CRUD 作業 (GET、PUT、POST、DELETE) 的 Web API 產生關聯。 但一個 API 控制器只需要實作一個控制器動作。
在此案例中,您會取得傳回的 WeatherForecast 項目完整清單。 GET 作業也可讓您透過傳入識別碼來擷取單一項目。 在 ASP.NET 中,您可以使用 [HttpGet("{id}")] 屬性來擷取單一項目。 您將在下一個練習中實作該屬性。
既然您已知道 Web API 控制器的基本元件,您現在就能建立自己的 PizzaController 類別。