ASP.NET Core 2.1 的新功能What's new in ASP.NET Core 2.1

本文會重點說明 ASP.NET Core 2.1 最重要的變更,附有相關文件的連結。This article highlights the most significant changes in ASP.NET Core 2.1, with links to relevant documentation.

SignalRSignalR

SignalR 已針對 ASP.NET Core 2.1 改寫。SignalR has been rewritten for ASP.NET Core 2.1. ASP.NET Core SignalR 包含數項改善:ASP.NET Core SignalR includes a number of improvements:

  • 簡化的向外延展模型。A simplified scale-out model.
  • 沒有 jQuery 相依性的新 JavaScript 用戶端。A new JavaScript client with no jQuery dependency.
  • 以 MessagePack 為基礎的新精簡二進位通訊協定。A new compact binary protocol based on MessagePack.
  • 支援自訂通訊協定。Support for custom protocols.
  • 新的資料流處理回應模型。A new streaming response model.
  • 支援以裸機 WebSockets 為基礎的用戶端。Support for clients based on bare WebSockets.

如需詳細資訊,請參閱 ASP.NET Core SignalRFor more information, see ASP.NET Core SignalR.

Razor 類別庫Razor class libraries

ASP.NET Core 2.1 讓您更容易在程式庫中建置並包含 Razor 型 UI,跨多個專案共用它。ASP.NET Core 2.1 makes it easier to build and include Razor-based UI in a library and share it across multiple projects. 新的 Razor SDK 能在可封裝到 NuGet 套件的類別庫專案中建置 Razor 檔案。The new Razor SDK enables building Razor files into a class library project that can be packaged into a NuGet package. 應用程式會自動探索並覆寫程式庫中的檢視和頁面。Views and pages in libraries are automatically discovered and can be overridden by the app. 藉由將 Razor 編譯整合至組建:By integrating Razor compilation into the build:

  • 大幅縮短應用程式的啟動時間。The app startup time is significantly faster.
  • 快速更新執行階段的 Razor 檢視和頁面仍然屬於反覆開發工作流程的一部分。Fast updates to Razor views and pages at runtime are still available as part of an iterative development workflow.

如需詳細資訊,請參閱使用 Razor 類別庫專案建立可重複使用的 UIFor more information, see Create reusable UI using the Razor Class Library project.

身分識別 UI 程式庫與 ScaffoldingIdentity UI library & scaffolding

ASP.NET Core 2.1 將 ASP.NET Core 身分識別提供為 Razor 類別庫ASP.NET Core 2.1 provides ASP.NET Core Identity as a Razor Class Library. 包含身分識別的應用程式可以套用新的身分識別 Scaffolder,以選擇性地新增包含在身分識別 Razor 類別庫 (RCL) 中的原始程式碼。Apps that include Identity can apply the new Identity scaffolder to selectively add the source code contained in the Identity Razor Class Library (RCL). 建議您產生原始程式碼,以便能夠修改程式碼並變更行為。You might want to generate source code so you can modify the code and change the behavior. 例如,您可以指示 Scaffolder 產生註冊使用的程式碼。For example, you could instruct the scaffolder to generate the code used in registration. 產生的程式碼優先於身分識別 RCL 中的相同程式碼。Generated code takes precedence over the same code in the Identity RCL.

包含驗證的應用程式可以套用身分識別 Scaffolder 以新增 RCL 身分識別套件。Apps that do not include authentication can apply the Identity scaffolder to add the RCL Identity package. 您可以選擇選取要產生的身分識別程式碼。You have the option of selecting Identity code to be generated.

如需詳細資訊,請參閱 ASP.NET Core 專案中的 Scaffold 身分識別For more information, see Scaffold Identity in ASP.NET Core projects.

HTTPSHTTPS

隨著安全性與隱私權日益受到重視,為 Web 應用程式啟用 HTTPS 極其重要。With the increased focus on security and privacy, enabling HTTPS for web apps is important. 在網站上強制執行 HTTPS 變得日益嚴格。HTTPS enforcement is becoming increasingly strict on the web. 不使用 HTTPS 的站台會被認為不安全。Sites that don’t use HTTPS are considered insecure. 瀏覽器 (Chromium、Mozilla) 開始強制執行必須從安全內容使用 Web 功能。Browsers (Chromium, Mozilla) are starting to enforce that web features must be used from a secure context. GDPR 需要使用 HTTPS 來保護使用者隱私。GDPR requires the use of HTTPS to protect user privacy. 雖然在生產環境中使用 HTTPS 非常重要,但在開發中使用 HTTPS 有助於避免發生部署問題 (例如不安全的連結)。While using HTTPS in production is critical, using HTTPS in development can help prevent issues in deployment (for example, insecure links). ASP.NET Core 2.1 包含多項改善,讓您更容易在開發中使用 HTTPS,以及在生產環境中設定 HTTPS。ASP.NET Core 2.1 includes a number of improvements that make it easier to use HTTPS in development and to configure HTTPS in production. 如需詳細資訊,請參閱強制執行 HTTPSFor more information, see Enforce HTTPS.

預設為開啟On by default

為方便保護網站開發,HTTPS 現在預設為啟用。To facilitate secure website development, HTTPS is now enabled by default. 自 2.1 開始,當有本機開發憑證存在時,Kestrel 會接聽 https://localhost:5001Starting in 2.1, Kestrel listens on https://localhost:5001 when a local development certificate is present. 開發憑證會建立於:A development certificate is created:

  • 您第一次使用 SDK,是 .NET Core SDK 首次執行體驗的一部分。As part of the .NET Core SDK first-run experience, when you use the SDK for the first time.
  • 手動使用新的 dev-certs 工具。Manually using the new dev-certs tool.

執行 dotnet dev-certs https --trust 以信任憑證。Run dotnet dev-certs https --trust to trust the certificate.

HTTPS 的重新導向和強制執行HTTPS redirection and enforcement

Web 應用程式通常需要同時接聽 HTTP 和 HTTPS,然後將所有 HTTP 流量重新導向至 HTTPS。Web apps typically need to listen on both HTTP and HTTPS, but then redirect all HTTP traffic to HTTPS. 在 2.1 中,特殊化的 HTTPS 重新導向中介軟體,會根據有無組態或是否引入繫結的伺服器連接埠,以聰明的方式重新導向。In 2.1, specialized HTTPS redirection middleware that intelligently redirects based on the presence of configuration or bound server ports has been introduced.

使用 HTTP 嚴格傳輸安全性通訊協定 (HSTS) 會進一步強制使用 HTTPS。Use of HTTPS can be further enforced using HTTP Strict Transport Security Protocol (HSTS). HSTS 指示瀏覽器一律透過 HTTPS 存取站台。HSTS instructs browsers to always access the site via HTTPS. ASP.NET Core 2.1 會新增支援最大存留期、子網域和 HSTS 預先載入清單選項的 HSTS 中介軟體。ASP.NET Core 2.1 adds HSTS middleware that supports options for max age, subdomains, and the HSTS preload list.

生產環境的組態Configuration for production

在生產環境中,必須明確設定 HTTPS。In production, HTTPS must be explicitly configured. 在 2.1 中,已新增為 Kestrel 設定 HTTPS 的預設組態結構描述。In 2.1, default configuration schema for configuring HTTPS for Kestrel has been added. 應用程式可以設定為使用下列:Apps can be configured to use:

GDPRGDPR

ASP.NET Core 提供 API 和範本以利符合某些 EU General Data Protection Regulation (GDPR) (EU 一般資料保護規定 (GDPR)) 需求。ASP.NET Core provides APIs and templates to help meet some of the EU General Data Protection Regulation (GDPR) requirements. 如需詳細資訊,請參閱 ASP.NET Core 的 GDPR 支援For more information, see GDPR support in ASP.NET Core. 範例應用程式示範如何使用及讓您測試新增至 ASP.NET Core 2.1 範本的大部分 GDPR 擴充點和 API。A sample app shows how to use and lets you test most of the GDPR extension points and APIs added to the ASP.NET Core 2.1 templates.

整合測試Integration tests

引進新套件簡化測試的建立和執行。A new package is introduced that streamlines test creation and execution. Microsoft.AspNetCore.Mvc.Testing 套件處理下列工作:The Microsoft.AspNetCore.Mvc.Testing package handles the following tasks:

  • 將相依性檔案 (*.deps) 從已測試的應用程式複製到測試專案的 bin 資料夾。Copies the dependency file (*.deps) from the tested app into the test project's bin folder.
  • 將內容的根目錄設定為經過測試之應用程式的專案根目錄,以便在執行測試時找到靜態檔案和頁面/檢視。Sets the content root to the tested app's project root so that static files and pages/views are found when the tests are executed.
  • 提供 WebApplicationFactory 類別來簡化以 TestServer 啟動載入經過測試的應用程式。Provides the WebApplicationFactory class to streamline bootstrapping the tested app with TestServer.

下列測試使用 xUnit 檢查具有成功狀態碼與正確 Content-type 標頭的 [索引] 頁面載入:The following test uses xUnit to check that the Index page loads with a success status code and with the correct Content-Type header:

public class BasicTests
    : IClassFixture<WebApplicationFactory<RazorPagesProject.Startup>>
{
    private readonly HttpClient _client;

    public BasicTests(WebApplicationFactory<RazorPagesProject.Startup> factory)
    {
        _client = factory.CreateClient();
    }

    [Fact]
    public async Task GetHomePage()
    {
        // Act
        var response = await _client.GetAsync("/");

        // Assert
        response.EnsureSuccessStatusCode(); // Status Code 200-299
        Assert.Equal("text/html; charset=utf-8",
            response.Content.Headers.ContentType.ToString());
    }
}

如需詳細資訊,請參閱整合測試主題。For more information, see the Integration tests topic.

[ApiController], ActionResult<T>[ApiController], ActionResult<T>

ASP.NET Core 2.1 新增新的程式設計慣例,讓您輕鬆建置全新和描述性的 Web API。ASP.NET Core 2.1 adds new programming conventions that make it easier to build clean and descriptive web APIs. ActionResult<T> 是新增的新類型,允許應用程式傳回回應類型或任何其他動作的結果 (類似於 IActionResult),同時仍然表示回應類型。ActionResult<T> is a new type added to allow an app to return either a response type or any other action result (similar to IActionResult), while still indicating the response type. [ApiController] 屬性也以選擇加入的方式新增至 Web API 特定慣例和行為中。The [ApiController] attribute has also been added as the way to opt in to Web API-specific conventions and behaviors.

如需詳細資訊,請參閱建置 Web API 與 ASP.NET CoreFor more information, see Build Web APIs with ASP.NET Core.

IHttpClientFactoryIHttpClientFactory

ASP.NET Core 2.1 包含新的 IHttpClientFactory 服務,讓您在應用程式中輕鬆設定和使用 HttpClient 的執行個體。ASP.NET Core 2.1 includes a new IHttpClientFactory service that makes it easier to configure and consume instances of HttpClient in apps. HttpClient 已經有委派可針對傳出 HTTP 要求連結在一起之處理常式的概念。HttpClient already has the concept of delegating handlers that could be linked together for outgoing HTTP requests. Factory:The factory:

  • 讓每個具名用戶端以更直覺的方式註冊 HttpClient 執行個體。Makes registering of instances of HttpClient per named client more intuitive.
  • 實作允許 Polly 原則用於重試、CircuitBreakers 等等的 Polly 處理常式。Implements a Polly handler that allows Polly policies to be used for Retry, CircuitBreakers, etc.

如需詳細資訊,請參閱初始化 HTTP 要求For more information, see Initiate HTTP Requests.

Kestrel 傳輸組態Kestrel transport configuration

隨著 ASP.NET Core 2.1 的發行,Kestrel 的預設傳輸不再根據 Libuv,而是改為根據受控通訊端。With the release of ASP.NET Core 2.1, Kestrel's default transport is no longer based on Libuv but instead based on managed sockets. 如需詳細資訊,請參閱 Kestrel 網頁伺服器實作:傳輸組態For more information, see Kestrel web server implementation: Transport configuration.

泛型主機建立器Generic host builder

已引入泛型主機建立器 (HostBuilder)。The Generic Host Builder (HostBuilder) has been introduced. 此建立器可用於不處理 HTTP 要求的應用程式 (傳訊、背景工作等等)。This builder can be used for apps that don't process HTTP requests (Messaging, background tasks, etc.).

如需詳細資訊,請參閱 .NET 泛型主機For more information, see .NET Generic Host.

已更新 SPA 範本Updated SPA templates

已更新適用於 Angular、React 和 React with Redux 的單頁應用程式範本,以使用標準的專案結構,並為每個架構建置系統。The Single Page Application templates for Angular, React, and React with Redux are updated to use the standard project structures and build systems for each framework.

Angular 範本以 Angular CLI 為基礎,React 範本以 create-react-app 為基礎。The Angular template is based on the Angular CLI, and the React templates are based on create-react-app.

如需詳細資訊,請參閱:For more information, see:

Razor Pages 搜尋 Razor 資產Razor Pages search for Razor assets

在 2.1 中,Razor Pages 會依所列順序在下列目錄中搜尋 Razor 資產 (如版面配置和部分):In 2.1, Razor Pages search for Razor assets (such as layouts and partials) in the following directories in the listed order:

  1. 目前的 Pages 資料夾。Current Pages folder.
  2. /Pages/Shared//Pages/Shared/
  3. /Views/Shared//Views/Shared/

區域中的 Razor PagesRazor Pages in an area

Razor Pages 現可支援區域Razor Pages now support areas. 若要查看區域範例,請使用個別的使用者帳戶建立新的 Razor Pages Web 應用程式。To see an example of areas, create a new Razor Pages web app with individual user accounts. 具有個別使用者帳戶的 Razor Pages Web 應用程式包含 /Areas/Identity/PagesA Razor Pages web app with individual user accounts includes /Areas/Identity/Pages.

MVC 相容性版本MVC compatibility version

SetCompatibilityVersion 方法可讓應用程式加入或退出 ASP.NET Core MVC 2.1 或更新版本所引入的可能重大行為變更。The SetCompatibilityVersion method allows an app to opt-in or opt-out of potentially breaking behavior changes introduced in ASP.NET Core MVC 2.1 or later.

如需詳細資訊,請參閱ASP.NET Core MVC 的相容性版本For more information, see ASP.NET Core MVC 的相容性版本.

從 2.0 遷移至 2.1Migrate from 2.0 to 2.1

請參閱從 ASP.NET Core 2.0 遷移到 2.1See Migrate from ASP.NET Core 2.0 to 2.1.

其他資訊Additional information

如需完整的變更清單,請參閱 ASP.NET Core 2.1 版本資訊For the complete list of changes, see the ASP.NET Core 2.1 Release Notes.