ASP.NET Core 會將 ASP.NET 4.x 的 MVC 和 Web API 應用程式模型結合成稱為 ASP.NET Core MVC 的單一程序設計模型。
本文說明如何將 開始使用 ASP.NET Web API 2 中建立的產品控制器移轉至 ASP.NET Core。
Prerequisites
- 具有 ASP.NET 和 Web 開發工作負載的 Visual Studio 2022。
- .NET 6 SDK
建立新的 ASP.NET Core Web API 專案
- 從 [檔案] 功能表選取 [新增]>[專案]。
- 在搜尋方塊中輸入 Web API。
- 選取 ASP.NET Core Web API 範本,然後選取 [下一步]。
- 在 [設定新專案] 對話框中,將專案命名 ProductsCore,然後選取 [下一步] 。
- 在 [其他資訊] 對話方塊中:
- 請確認 Framework 是 .NET 6.0(長期支援)。
- 確認勾選 「使用控制器」(取消勾選以使用最小 API) 選項。
- 取消勾選 啟用 OpenAPI 支援。
- 選取 ,創建。
拿掉 WeatherForecast 樣本檔案
- 從新的
WeatherForecast.cs專案中移除Controllers/WeatherForecastController.cs和 範例檔案。 - 開啟 [屬性] 開啟\launchSettings.js。
- 將
launchUrl屬性從weatherforcast變更為productscore。
ASP.NET Core Web API 的組態
ASP.NET Core 不會使用 App_Start 資料夾或 Global.asax 檔案。 web.config 檔案會在發佈時新增。 如需詳細資訊,請參閱 web.config 檔案。
Program.cs 檔案:
- 取代 Global.asax。
- 處理所有應用程式啟動工作。
如需詳細資訊,請參閱 ASP.NET Core 中的應用程式啟動。
下列顯示 ASP.NET Core Program.cs 檔案中的應用程式啟動程式代碼:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
複製 產品 模型
- 在 [方案總管] 中,用滑鼠右鍵點擊專案。 選擇 新增>新資料夾。 將資料夾 命名為模型。
- 以滑鼠右鍵按兩下 [Models] 資料夾。 選擇 ,新增>類別。 將類別命名為 Product 並選取 新增。
- 用以下內容取代範本模型程式碼:
namespace ProductsCore.Models
{
public class Product
{
public int Id { get; set; }
public string? Name { get; set; }
public string? Category { get; set; }
public decimal Price { get; set; }
}
}
上述醒目提示的程式代碼會變更下列內容:
- 已新增
?批注,將Name和Category屬性宣告為可為 Null 的參考型別。
藉由利用 C# 8 中引進的Nullable 功能,ASP.NET Core 可以在處理參考型別時提供額外的程式代碼流程分析和編譯時間安全性。 例如,防止 null 參考例外狀況。
在此情況下,意圖是 Name 和 Category 可以是可為 Null 的類型。
在 .NET 6 專案中,ASP.NET Core 預設會啟用可為空的參考型別。 如需詳細資訊,請參閱 可為 Null 的參考型別。
複製 ProductsController
- 以滑鼠右鍵按兩下 [Controllers] 資料夾。
- 選取 新增 > 控制器...。
- 在 [新增 Scaffolded 專案項目] 對話框中,選取 [Mvc 控制器 - 空白],然後選取 [新增]。
- 將控制器命名為 ProductsController,然後選取 [新增]。
- 將範本控制器程式碼替換為以下內容:
using Microsoft.AspNetCore.Mvc;
using ProductsCore.Models;
namespace ProductsCore.Controllers;
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
Product[] products = new Product[]
{
new Product
{
Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1
},
new Product
{
Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M
},
new Product
{
Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M
}
};
[HttpGet]
public IEnumerable<Product> GetAllProducts()
{
return products;
}
[HttpGet("{id}")]
public ActionResult<Product> GetProduct(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
return NotFound();
}
return product;
}
}
前面突顯的程式代碼會修改下列內容,以移轉至 ASP.NET Core:
針對 ASP.NET Core 中不存在的下列 ASP.NET 4.x 元件,移除 using 語句:
-
ApiController類別 -
System.Web.Http命名空間 -
IHttpActionResult介面
-
將
using ProductsApp.Models;語句變更為using ProductsCore.Models;。將根命名空間設定為
ProductsCore。將
ApiController變更為 ControllerBase。新增
using Microsoft.AspNetCore.Mvc;以解決ControllerBase參考。將
GetProduct動作的傳回型別從IHttpActionResult變更為ActionResult<Product>。 如需詳細資訊,請參閱 控制器動作傳回類型。將
GetProduct動作的return語句簡化為下列語句:return product;新增下列屬性,這些屬性會在下一節中說明:
[Route("api/[controller]")][ApiController][HttpGet][HttpGet("{id}")]
Routing
ASP.NET Core 提供最少的裝載模型,其中端點路由中間件會包裝整個中間件管線,因此路由可以直接新增至 WebApplication,而不需要明確呼叫 UseEndpoints 或 UseRouting 來註冊路由。
UseRouting 仍可用來指定路由比對發生的位置,但如果中間件管線開頭應該比對路由,則不需要明確呼叫 UseRouting。
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
注意: 路由直接新增至管線 WebApplication 執行 。
移轉 ProductsController 中的路由
已遷移的 ProductsController 包含以下醒目的屬性:
using Microsoft.AspNetCore.Mvc;
using ProductsCore.Models;
namespace ProductsCore.Controllers;
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
Product[] products = new Product[]
{
new Product
{
Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1
},
new Product
{
Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M
},
new Product
{
Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M
}
};
[HttpGet]
public IEnumerable<Product> GetAllProducts()
{
return products;
}
[HttpGet("{id}")]
public ActionResult<Product> GetProduct(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
return NotFound();
}
return product;
}
}
[Route]屬性 設定控制器的屬性路由 模式。[ApiController]屬性可讓屬性路由成為此控制器中所有動作的需求。屬性路由支援令牌,例如
[controller]和[action]。 在執行階段,每個令牌會被替換成已套用屬性的控制器名稱或動作名稱。 代幣:- 減少或排除對路由使用硬式編碼字串的需求。
- 確定套用自動重新命名重構時,路由會與對應的控制器和動作保持同步。
HTTP 取得要求會針對具有下列屬性的
ProductController動作啟用:-
[HttpGet]屬性套用至GetAllProducts動作。 -
[HttpGet("{id}")]屬性套用至GetProduct動作。
-
執行已移轉的專案,並瀏覽至 /api/products。 例如:https://localhost:<port>/api/products。 隨即出現三個產品的完整清單。 瀏覽至 /api/products/1。 第一個產品隨即出現。
其他資源
- 使用 ASP.NET Core 建立 Web API
- ASP.NET Core Web API 中的控制器動作傳回類型
- ASP.NET Core MVC 的相容性版本
本文示範從 ASP.NET 4.x Web API 移轉至 ASP.NET Core MVC 所需的步驟。
Prerequisites
- Visual Studio 2019 16.4 或更新版本,其中包含 ASP.NET 和網頁程式開發工作負載
- .NET Core 3.1 SDK
檢閱 ASP.NET 4.x Web API 專案
本文使用在《開始使用 ASP.NET Web API 2》中建立的ProductsApp 專案。 在該專案中,基本 ASP.NET 4.x Web API 項目設定如下。
在 Global.asax.cs中,會呼叫 WebApiConfig.Register:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Routing;
namespace ProductsApp
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
}
WebApiConfig 類別位於 App_Start 資料夾中,且具有靜態 Register 方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace ProductsApp
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
先前的課程:
- 設定 屬性路由,但實際上並未使用。
- 設定路由表。
範例程式代碼預期 URL 符合
/api/{controller}/{id}格式,{id}為選擇性。
下列各節示範將 Web API 專案移轉至 ASP.NET Core MVC。
建立目的地專案
在 Visual Studio 中建立新的空白解決方案,並新增要移轉的 ASP.NET 4.x Web API 專案:
- 從 [檔案] 功能表選取 [新增]>[專案]。
- 選擇 空白解決方案 範本,然後選擇 [下一步]。
- 將方案命名為 WebAPIMigration。 選取 ,創建。
- 將現有的 ProductsApp 專案新增至方案。
新增要移轉至的 API 專案:
- 將新的 ASP.NET Core Web 應用程式 專案新增至方案。
- 在 [設定新專案] 對話框中,將專案名稱設定為 ProductsCore,然後選取 [建立 ]。
- 在 [[建立新的 ASP.NET Core Web 應用程式] 對話框中,確認已選取 .NET Core 和 ASP.NET Core 3.1。 選取 [API] 專案範本,然後選取 [確定]。
- 從新的
WeatherForecast.cs專案中移除Controllers/WeatherForecastController.cs和 範例檔案。
方案現在包含兩個專案。 下列各節說明將 ProductsApp 項目的內容移轉至 ProductsCore 專案。
移轉組態
ASP.NET Core 不會使用 App_Start 資料夾或 Global.asax 檔案。 此外,web.config 檔案會在發佈時新增。
Startup 類別:
- 取代 Global.asax。
- 處理所有應用程式啟動工作。
如需詳細資訊,請參閱 ASP.NET Core 中的應用程式啟動。
移轉模型和控制器
以下程式碼顯示要在 ASP.NET Core 中更新的 ProductsController:
using ProductsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;
namespace ProductsApp.Controllers
{
public class ProductsController : ApiController
{
Product[] products = new Product[]
{
new Product
{
Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1
},
new Product
{
Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M
},
new Product
{
Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M
}
};
public IEnumerable<Product> GetAllProducts()
{
return products;
}
public IHttpActionResult GetProduct(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
}
}
更新 ProductsController 以適用於 ASP.NET Core:
- 將
Controllers/ProductsController.cs和 Models 資料夾從原始項目複製到新的專案。 - 將已複製的檔案的根命名空間變更為
ProductsCore。 - 將
using ProductsApp.Models;語句更新為using ProductsCore.Models;。
ASP.NET Core 中不存在下列元件:
-
ApiController類別 -
System.Web.Http命名空間 -
IHttpActionResult介面
進行下列變更:
將
ApiController變更為 ControllerBase。 新增using Microsoft.AspNetCore.Mvc;用於解析ControllerBase參考。刪除
using System.Web.Http;。將
GetProduct動作的傳回型別從IHttpActionResult變更為ActionResult<Product>。將
GetProduct動作的return語句簡化為下列各項:return product;
設定路由
ASP.NET Core API 項目樣本會在產生的程式代碼中包含端點路由設定。
下列 UseRouting 和 UseEndpoints 呼叫:
- 在 中介軟體 管線中註冊路由匹配和端點執行。
- 取代 ProductsApp 專案的
App_Start/WebApiConfig.cs檔案。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
設定路由,如下所示:
使用下列屬性標記
ProductsController類別:[Route("api/[controller]")] [ApiController]上述
[Route]屬性會設定控制器的屬性路由模式。[ApiController]屬性可讓屬性路由成為此控制器中所有動作的需求。屬性路由支援令牌,例如
[controller]和[action]。 在執行階段,每個令牌會被替換成已套用屬性的控制器名稱或動作名稱。 代幣:- 減少專案中的魔術字串數目。
- 確定套用自動重新命名重構時,路由會與對應的控制器和動作保持同步。
啟用 HTTP Get 請求至
ProductsController操作:- 將
[HttpGet]屬性套用至GetAllProducts動作。 - 將
[HttpGet("{id}")]屬性套用至GetProduct動作。
- 將
執行已移轉的專案,並瀏覽至 /api/products。 隨即出現三個產品的完整清單。 瀏覽至 /api/products/1。 第一個產品隨即出現。
其他資源
- 使用 ASP.NET Core 建立 Web API
- ASP.NET Core Web API 中的控制器動作傳回類型
- ASP.NET Core MVC 的相容性版本