從 ASP.NET Core 2.2 遷移至3。0Migrate from ASP.NET Core 2.2 to 3.0

Scott AddieRick AndersonBy Scott Addie and Rick Anderson

本文說明如何將現有的 ASP.NET Core 2.2 專案更新為 ASP.NET Core 3.0。This article explains how to update an existing ASP.NET Core 2.2 project to ASP.NET Core 3.0. 建立新的 ASP.NET Core 3.0 專案時,可能會有説明:It might be helpful to create a new ASP.NET Core 3.0 project to:

  • 與 ASP.NET Core 2.2 程式碼比較。Compare with the ASP.NET Core 2.2 code.
  • 將相關的變更複製到您的 ASP.NET Core 3.0 專案。Copy the relevant changes to your ASP.NET Core 3.0 project.

必要條件Prerequisites

更新 global.json 中的 .NET Core SDK 版本Update .NET Core SDK version in global.json

如果您的解決方案依賴檔案 上的global.js ,以特定的 .NET Core SDK 版本為目標,請將其 version 屬性更新為安裝在您電腦上的3.0 版:If your solution relies upon a global.json file to target a specific .NET Core SDK version, update its version property to the 3.0 version installed on your machine:

{
  "sdk": {
    "version": "3.0.100"
  }
}

更新專案檔Update the project file

更新目標 FrameworkUpdate the Target Framework

ASP.NET Core 3.0 和更新版本只會在 .NET Core 上執行。ASP.NET Core 3.0 and later only run on .NET Core. 目標 Framework 標記 (TFM) 設定為 netcoreapp3.0Set the Target Framework Moniker (TFM) to netcoreapp3.0:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
  </PropertyGroup>

</Project>

移除淘汰的套件參考Remove obsolete package references

ASP.NET Core 3.0 不會產生大量的 NuGet 套件。A large number of NuGet packages aren't produced for ASP.NET Core 3.0. 您應該從專案檔中移除這類套件參考。Such package references should be removed from your project file. 針對 ASP.NET Core 2.2 web 應用程式,請考慮下列專案檔:Consider the following project file for an ASP.NET Core 2.2 web app:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.App"/>
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
  </ItemGroup>

</Project>

ASP.NET Core 3.0 的已更新專案檔:The updated project file for ASP.NET Core 3.0:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
  </PropertyGroup>

</Project>

更新的 ASP.NET Core 3.0 專案檔:The updated ASP.NET Core 3.0 project file:

  • <PropertyGroup> 中:In the <PropertyGroup>:

    • 將 TFM 更新為 netcoreapp3.0Updates the TFM to netcoreapp3.0
    • 移除專案 <AspNetCoreHostingModel>Removes the <AspNetCoreHostingModel> element. 如需詳細資訊,請參閱本檔中的同 進程裝載模型For more information, see In-process hosting model in this document.
  • <ItemGroup> 中:In the <ItemGroup>:

    • Microsoft.AspNetCore.App 已移除。Microsoft.AspNetCore.App is removed. 如需詳細資訊,請參閱本檔中的 架構參考For more information, see Framework reference in this document.
    • Microsoft.AspNetCore.Razor.Design 已移除,且已在下列套件清單中不再產生。Microsoft.AspNetCore.Razor.Design is removed and in the following list of packages no longer being produced.

若要查看不再產生之套件的完整清單,請選取下列展開清單:To see the full list of packages that are no longer produced, select the following expand list:

按一下以展開不再產生的套件清單Click to expand the list of packages no longer being produced
  • Microsoft.AspNetCoreMicrosoft.AspNetCore
  • Microsoft.AspNetCore.AllMicrosoft.AspNetCore.All
  • Microsoft.AspNetCore.AppMicrosoft.AspNetCore.App
  • Microsoft.AspNetCore.AntiforgeryMicrosoft.AspNetCore.Antiforgery
  • Microsoft.AspNetCore.AuthenticationMicrosoft.AspNetCore.Authentication
  • Microsoft.AspNetCore.Authentication.AbstractionsMicrosoft.AspNetCore.Authentication.Abstractions
  • AspNetCore 驗證。 Cookie!Microsoft.AspNetCore.Authentication.Cookies
  • Microsoft.AspNetCore.Authentication.CoreMicrosoft.AspNetCore.Authentication.Core
  • Microsoft.AspNetCore.Authentication.OAuthMicrosoft.AspNetCore.Authentication.OAuth
  • Microsoft.AspNetCore.Authorization.PolicyMicrosoft.AspNetCore.Authorization.Policy
  • AspNetCore。 Cookie政策Microsoft.AspNetCore.CookiePolicy
  • Microsoft.AspNetCore.CorsMicrosoft.AspNetCore.Cors
  • Microsoft.AspNetCore.DiagnosticsMicrosoft.AspNetCore.Diagnostics
  • Microsoft.AspNetCore.Diagnostics.HealthChecksMicrosoft.AspNetCore.Diagnostics.HealthChecks
  • Microsoft.AspNetCore.HostFilteringMicrosoft.AspNetCore.HostFiltering
  • Microsoft.AspNetCore.HostingMicrosoft.AspNetCore.Hosting
  • Microsoft.AspNetCore.Hosting.AbstractionsMicrosoft.AspNetCore.Hosting.Abstractions
  • Microsoft.AspNetCore.Hosting.Server.AbstractionsMicrosoft.AspNetCore.Hosting.Server.Abstractions
  • Microsoft.AspNetCore.HttpMicrosoft.AspNetCore.Http
  • Microsoft.AspNetCore.Http.AbstractionsMicrosoft.AspNetCore.Http.Abstractions
  • Microsoft.AspNetCore.Http.ConnectionsMicrosoft.AspNetCore.Http.Connections
  • Microsoft.AspNetCore.Http.ExtensionsMicrosoft.AspNetCore.Http.Extensions
  • Microsoft.AspNetCore.HttpOverridesMicrosoft.AspNetCore.HttpOverrides
  • Microsoft.AspNetCore.HttpsPolicyMicrosoft.AspNetCore.HttpsPolicy
  • AspNetCore。IdentityMicrosoft.AspNetCore.Identity
  • Microsoft.AspNetCore.LocalizationMicrosoft.AspNetCore.Localization
  • Microsoft.AspNetCore.Localization.RoutingMicrosoft.AspNetCore.Localization.Routing
  • Microsoft.AspNetCore.MvcMicrosoft.AspNetCore.Mvc
  • Microsoft.AspNetCore.Mvc.AbstractionsMicrosoft.AspNetCore.Mvc.Abstractions
  • Microsoft.AspNetCore.Mvc.AnalyzersMicrosoft.AspNetCore.Mvc.Analyzers
  • Microsoft.AspNetCore.Mvc.ApiExplorerMicrosoft.AspNetCore.Mvc.ApiExplorer
  • Microsoft.AspNetCore.Mvc.Api.AnalyzersMicrosoft.AspNetCore.Mvc.Api.Analyzers
  • Microsoft.AspNetCore.Mvc.CoreMicrosoft.AspNetCore.Mvc.Core
  • Microsoft.AspNetCore.Mvc.CorsMicrosoft.AspNetCore.Mvc.Cors
  • Microsoft.AspNetCore.Mvc.DataAnnotationsMicrosoft.AspNetCore.Mvc.DataAnnotations
  • Microsoft.AspNetCore.Mvc.Formatters.JsonMicrosoft.AspNetCore.Mvc.Formatters.Json
  • Microsoft.AspNetCore.Mvc.Formatters.XmlMicrosoft.AspNetCore.Mvc.Formatters.Xml
  • Microsoft.AspNetCore.Mvc.LocalizationMicrosoft.AspNetCore.Mvc.Localization
  • AspNetCore。RazorMicrosoft.AspNetCore.Mvc.Razor
  • AspNetCore Razor 。>microsoft.aspnetcore.mvc.razor.viewcompilationMicrosoft.AspNetCore.Mvc.Razor.ViewCompilation
  • AspNetCore。 Razor頁面Microsoft.AspNetCore.Mvc.RazorPages
  • Microsoft.AspNetCore.Mvc.TagHelpersMicrosoft.AspNetCore.Mvc.TagHelpers
  • Microsoft.AspNetCore.Mvc.ViewFeaturesMicrosoft.AspNetCore.Mvc.ViewFeatures
  • AspNetCore。RazorMicrosoft.AspNetCore.Razor
  • AspNetCore Razor 。運行Microsoft.AspNetCore.Razor.Runtime
  • AspNetCore Razor 。設計Microsoft.AspNetCore.Razor.Design
  • Microsoft.AspNetCore.ResponseCachingMicrosoft.AspNetCore.ResponseCaching
  • Microsoft.AspNetCore.ResponseCaching.AbstractionsMicrosoft.AspNetCore.ResponseCaching.Abstractions
  • Microsoft.AspNetCore.ResponseCompressionMicrosoft.AspNetCore.ResponseCompression
  • Microsoft.AspNetCore.RewriteMicrosoft.AspNetCore.Rewrite
  • Microsoft.AspNetCore.RoutingMicrosoft.AspNetCore.Routing
  • Microsoft.AspNetCore.Routing.AbstractionsMicrosoft.AspNetCore.Routing.Abstractions
  • Microsoft.AspNetCore.Server.HttpSysMicrosoft.AspNetCore.Server.HttpSys
  • Microsoft.AspNetCore.Server.IISMicrosoft.AspNetCore.Server.IIS
  • Microsoft.AspNetCore.Server.IISIntegrationMicrosoft.AspNetCore.Server.IISIntegration
  • Microsoft.AspNetCore.Server.KestrelMicrosoft.AspNetCore.Server.Kestrel
  • Microsoft.AspNetCore.Server.Kestrel.CoreMicrosoft.AspNetCore.Server.Kestrel.Core
  • Microsoft.AspNetCore.Server.Kestrel.HttpsMicrosoft.AspNetCore.Server.Kestrel.Https
  • Microsoft.AspNetCore.Server.Kestrel.Transport.AbstractionsMicrosoft.AspNetCore.Server.Kestrel.Transport.Abstractions
  • Microsoft.AspNetCore.Server.Kestrel.Transport.SocketsMicrosoft.AspNetCore.Server.Kestrel.Transport.Sockets
  • Microsoft.AspNetCore.SessionMicrosoft.AspNetCore.Session
  • AspNetCore。SignalRMicrosoft.AspNetCore.SignalR
  • AspNetCore SignalR 。核心Microsoft.AspNetCore.SignalR.Core
  • Microsoft.AspNetCore.StaticFilesMicrosoft.AspNetCore.StaticFiles
  • Microsoft.AspNetCore.WebSocketsMicrosoft.AspNetCore.WebSockets
  • Microsoft.AspNetCore.WebUtilitiesMicrosoft.AspNetCore.WebUtilities
  • Microsoft.Net.Http.Headers Microsoft.Net.Http.Headers

檢查重大變更Review breaking changes

檢查重大變更Review breaking changes

架構參考Framework reference

您可以透過上述其中一個套件取得 ASP.NET Core 的功能,作為 Microsoft.AspNetCore.App 共用架構的一部分。Features of ASP.NET Core that were available through one of the packages listed above are available as part of the Microsoft.AspNetCore.App shared framework. 共用架構是安裝在電腦上的一組元件 (.dll檔案) ,其中包含執行時間元件和目標套件。The shared framework is the set of assemblies (.dll files) that are installed on the machine and includes a runtime component and a targeting pack. 如需詳細資訊,請參閱共用的架構 (英文)。For more information, see The shared framework.

  • 以 SDK 為目標的專案會 Microsoft.NET.Sdk.Web 隱含地參考 Microsoft.AspNetCore.App 架構。Projects that target the Microsoft.NET.Sdk.Web SDK implicitly reference the Microsoft.AspNetCore.App framework.

    這些專案不需要額外的參考:No additional references are required for these projects:

    <Project Sdk="Microsoft.NET.Sdk.Web">
      <PropertyGroup>
        <TargetFramework>netcoreapp3.0</TargetFramework>
      </PropertyGroup>
        ...
    </Project>
    
  • Microsoft.NET.Sdk以或 SDK 為目標的專案 Microsoft.NET.Sdk.Razor 應該將明確加入 FrameworkReferenceMicrosoft.AspNetCore.AppProjects that target Microsoft.NET.Sdk or Microsoft.NET.Sdk.Razor SDK, should add an explicit FrameworkReference to Microsoft.AspNetCore.App:

    <Project Sdk="Microsoft.NET.Sdk.Razor">
      <PropertyGroup>
        <TargetFramework>netcoreapp3.0</TargetFramework>
      </PropertyGroup>
    
      <ItemGroup>
        <FrameworkReference Include="Microsoft.AspNetCore.App" />
      </ItemGroup>
        ...
    </Project>
    

使用 Docker 的 Framework 相依組建Framework-dependent builds using Docker

以 Framework 相依的主控台應用程式組建,使用相依于 ASP.NET Core 共用架構 的套件可能會提供下列執行階段錯誤:Framework-dependent builds of console apps that use a package that depends on the ASP.NET Core shared framework may give the following runtime error:

It was not possible to find any compatible framework version
The specified framework 'Microsoft.AspNetCore.App', version '3.0.0' was not found.
  - No frameworks were found.

Microsoft.AspNetCore.App 是包含 ASP.NET Core 執行時間,而且只存在於 dotnet/Core/aspnet Docker 映射上的共用架構。Microsoft.AspNetCore.App is the shared framework containing the ASP.NET Core runtime and is only present on the dotnet/core/aspnet Docker image. 3.0 SDK 會使用 ASP.NET Core 來減少 framework 相依組建的大小,方法是不包含共用架構中所提供的重複程式庫複本。The 3.0 SDK reduces the size of framework-dependent builds using ASP.NET Core by not including duplicate copies of libraries that are available in the shared framework. 這可能會節省最多 18 MB,但需要 ASP.NET Core 執行時間存在/安裝,才能執行應用程式。This is a potential savings of up to 18 MB, but it requires that the ASP.NET Core runtime be present / installed to run the app.

若要判斷應用程式是否相依 (ASP.NET Core 共用架構上的直接或間接) ,請檢查應用程式組建/發佈期間產生的檔案 runtimeconfig.jsTo determine if the app has a dependency (either direct or indirect) on the ASP.NET Core shared framework, examine the runtimeconfig.json file generated during a build/publish of your app. 下列 JSON 檔案顯示 ASP.NET Core 共用架構的相依性:The following JSON file shows a dependency on the ASP.NET Core shared framework:

{
  "runtimeOptions": {
    "tfm": "netcoreapp3.0",
    "framework": {
      "name": "Microsoft.AspNetCore.App",
      "version": "3.0.0"
    },
    "configProperties": {
      "System.GC.Server": true
    }
  }
}

如果您的應用程式使用 Docker,請使用包含 ASP.NET Core 3.0 的基底映射。If your app is using Docker, use a base image that includes ASP.NET Core 3.0. 例如: docker pull mcr.microsoft.com/dotnet/core/aspnet:3.0For example, docker pull mcr.microsoft.com/dotnet/core/aspnet:3.0.

新增已移除元件的套件參考Add package references for removed assemblies

ASP.NET Core 3.0 會移除先前屬於封裝參考一部分的元件 Microsoft.AspNetCore.AppASP.NET Core 3.0 removes some assemblies that were previously part of the Microsoft.AspNetCore.App package reference. 若要將已移除的元件視覺化,請比較兩個共用的架構資料夾。To visualize which assemblies were removed, compare the two shared framework folders. 例如,2.2.7 和3.0.0 版本的比較:For example, a comparison of versions 2.2.7 and 3.0.0:

共用架構元件比較

若要繼續使用已移除元件所提供的功能,請參考對應套件的3.0 版本:To continue using features provided by the removed assemblies, reference the 3.0 versions of the corresponding packages:

啟動變更Startup changes

下圖顯示 ASP.NET Core 2.2 Razor 頁面 Web 應用程式中已刪除及已變更的行:The following image shows the deleted and changed lines in an ASP.NET Core 2.2 Razor Pages Web app:

ASP.NET Core 2.2::: no-loc (Razor) ::: Web 應用程式中已刪除和變更的行

在上圖中,刪除的程式碼以紅色顯示。In the preceding image, deleted code is shown in red. 刪除的程式碼並不會顯示 cookie 在比較檔案之前刪除的選項代碼。The deleted code doesn't show cookie options code, which was deleted prior to comparing the files.

下圖顯示 ASP.NET Core 3.0 Razor 頁面 Web 應用程式中新增和變更的行:The following image shows the added and changed lines in an ASP.NET Core 3.0 Razor Pages Web app:

在 ASP.NET Core 3.0::: no-loc (Razor) ::: Web 應用程式中新增和變更的行

在上圖中,已加入的程式碼會以綠色顯示。In the preceding image, added code is shown in green. 如需下列變更的相關資訊:For information on the following changes:

分析器支援Analyzer support

Microsoft.NET.Sdk.Web以隱含參考分析器為目標的專案,先前隨附于AspNetCore封裝中。Projects that target Microsoft.NET.Sdk.Web implicitly reference analyzers previously shipped as part of the Microsoft.AspNetCore.Mvc.Analyzers package. 不需要額外的參考來啟用這些。No additional references are required to enable these.

如果您的應用程式使用先前使用AspNetCore隨附的api 分析器,請編輯您的專案檔,以參考隨附于 .net Core Web SDK 的分析器:If your app uses API analyzers previously shipped using the Microsoft.AspNetCore.Mvc.Api.Analyzers package, edit your project file to reference the analyzers shipped as part of the .NET Core Web SDK:

<Project Sdk="Microsoft.NET.Sdk.Web">
    <PropertyGroup>
        <TargetFramework>netcoreapp3.0</TargetFramework>
        <IncludeOpenAPIAnalyzers>true</IncludeOpenAPIAnalyzers>
    </PropertyGroup>

    ...
</Project>

Razor 類別庫Razor Class Library

Razor 提供 MVC UI 元件的類別庫專案必須設定專案檔 AddRazorSupportForMvc 中的屬性:Razor Class Library projects that provide UI components for MVC must set the AddRazorSupportForMvc property in the project file:

<PropertyGroup>
  <AddRazorSupportForMvc>true</AddRazorSupportForMvc>
</PropertyGroup>

同處理序裝載模型In-process hosting model

專案預設為 ASP.NET Core 3.0 或更新版本中的同 進程裝載模型Projects default to the in-process hosting model in ASP.NET Core 3.0 or later. 您可以選擇性地移除 <AspNetCoreHostingModel> 專案檔中的屬性(如果其值為) InProcessYou may optionally remove the <AspNetCoreHostingModel> property in the project file if its value is InProcess.

KestrelKestrel

組態Configuration

將 Kestrel 設定遷移至 (Program.cs) 所提供的web 主機建立器 ConfigureWebHostDefaultsProgram.csMigrate Kestrel configuration to the web host builder provided by ConfigureWebHostDefaults (Program.cs):

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.ConfigureKestrel(serverOptions =>
            {
                // Set properties and call methods on options
            })
            .UseStartup<Startup>();
        });

如果應用程式以手動方式建立主機 HostBuilder ,請在 UseKestrel 中的 web 主機建立器上呼叫 ConfigureWebHostDefaultsIf the app creates the host manually with HostBuilder, call UseKestrel on the web host builder in ConfigureWebHostDefaults:

public static void Main(string[] args)
{
    var host = new HostBuilder()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseKestrel(serverOptions =>
            {
                // Set properties and call methods on options
            })
            .UseIISIntegration()
            .UseStartup<Startup>();
        })
        .Build();

    host.Run();
}

連接中介軟體會取代連接介面卡Connection Middleware replaces Connection Adapters

Microsoft.AspNetCore.Server.Kestrel.Core.Adapter.Internal.IConnectionAdapter 從 Kestrel 中移除連接介面卡 () 。Connection Adapters (Microsoft.AspNetCore.Server.Kestrel.Core.Adapter.Internal.IConnectionAdapter) have been removed from Kestrel. 以連接中介軟體取代連接介面卡。Replace Connection Adapters with Connection Middleware. 連接中介軟體類似于 ASP.NET Core 管線中的 HTTP 中介軟體,但較低層級的連接。Connection Middleware is similar to HTTP Middleware in the ASP.NET Core pipeline but for lower-level connections. HTTPS 和連接記錄:HTTPS and connection logging:

  • 已從連接配接器移至連線中介軟體。Have been moved from Connection Adapters to Connection Middleware.
  • 這些擴充方法的運作方式與舊版 ASP.NET Core 一樣。These extension methods work as in previous versions of ASP.NET Core.

如需詳細資訊,請參閱 Kestrel 文章 >listenoptions 一節中的 TlsFilterConnectionHandler 範例For more information, see the TlsFilterConnectionHandler example in the ListenOptions.Protocols section of the Kestrel article.

傳輸抽象層已移動並公開Transport abstractions moved and made public

Kestrel 傳輸層已公開為中的公用介面 Connections.AbstractionsThe Kestrel transport layer has been exposed as a public interface in Connections.Abstractions. 作為這些更新的一部分:As part of these updates:

  • Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions 和相關聯的類型已移除。Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions and associated types have been removed.
  • NoDelay 已從移 ListenOptions 至傳輸選項。NoDelay was moved from ListenOptions to the transport options.
  • Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal.SchedulingMode 已從移除 KestrelServerOptionsMicrosoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal.SchedulingMode was removed from KestrelServerOptions.

如需詳細資訊,請參閱下列 GitHub 資源:For more information, see the following GitHub resources:

Kestrel 要求尾端標頭Kestrel Request trailer headers

針對以舊版 ASP.NET Core 為目標的應用程式:For apps that target earlier versions of ASP.NET Core:

  • Kestrel 會將 HTTP/1.1 區塊尾端標頭新增至要求標頭集合。Kestrel adds HTTP/1.1 chunked trailer headers into the request headers collection.
  • 要求主體讀取至結尾之後,就可以使用尾端。Trailers are available after the request body is read to the end.

這會導致在標頭和結尾之間有一些不明確的問題,因此尾端已移至新的集合 (RequestTrailerExtensions) 在3.0 中。This causes some concerns about ambiguity between headers and trailers, so the trailers have been moved to a new collection (RequestTrailerExtensions) in 3.0.

HTTP/2 要求尾端為:HTTP/2 request trailers are:

  • 在 ASP.NET Core 2.2 中無法使用。Not available in ASP.NET Core 2.2.
  • 以3.0 為形式提供 RequestTrailerExtensionsAvailable in 3.0 as RequestTrailerExtensions.

有新的要求延伸方法可存取這些尾端。New request extension methods are present to access these trailers. 和 HTTP/1.1 一樣,在要求主體讀取至結尾之後可使用尾端。As with HTTP/1.1, trailers are available after the request body is read to the end.

在3.0 版本中, RequestTrailerExtensions 可以使用下列方法:For the 3.0 release, the following RequestTrailerExtensions methods are available:

  • GetDeclaredTrailers:取得要求 Trailer 標頭,此標頭會列出主體之後所預期的尾端。GetDeclaredTrailers: Gets the request Trailer header that lists which trailers to expect after the body.
  • SupportsTrailers:指出要求是否支援接收尾端標頭。SupportsTrailers: Indicates if the request supports receiving trailer headers.
  • CheckTrailersAvailable:檢查要求是否支援結尾和是否可讀取。CheckTrailersAvailable: Checks if the request supports trailers and if they're available to be read. 這種檢查不會假設有尾端可供讀取。This check doesn't assume that there are trailers to read. 即使這個方法傳回,也可能不會讀取任何尾端 trueThere might be no trailers to read even if true is returned by this method.
  • GetTrailer:從回應取得要求的尾端標頭。GetTrailer: Gets the requested trailing header from the response. SupportsTrailers在呼叫之前檢查 GetTrailerNotSupportedException 如果要求不支援尾端標頭,則可能會發生。Check SupportsTrailers before calling GetTrailer, or a NotSupportedException may occur if the request doesn't support trailing headers.

如需詳細資訊,請參閱 將要求尾端放在個別的集合中 (dotnet/AspNetCore #10410) For more information, see Put request trailers in a separate collection (dotnet/AspNetCore #10410).

AllowSynchronousIO 已停用AllowSynchronousIO disabled

AllowSynchronousIO 啟用或停用同步 i/o Api,例如 HttpRequest.Body.ReadHttpResponse.Body.WriteStream.FlushAllowSynchronousIO enables or disables synchronous I/O APIs, such as HttpRequest.Body.Read, HttpResponse.Body.Write, and Stream.Flush. 這些 Api 是執行緒耗盡的來源,導致應用程式損毀。These APIs are a source of thread starvation leading to app crashes. 在3.0 中, AllowSynchronousIO 預設為停用。In 3.0, AllowSynchronousIO is disabled by default. 如需詳細資訊,請參閱 Kestrel 文章中的同步 i/o 一節For more information, see the Synchronous I/O section in the Kestrel article.

如果需要同步 i/o,您可以 AllowSynchronousIO 在呼叫時( ConfigureKestrel 例如,如果使用 Kestrel) )在 (使用的伺服器上設定選項來啟用它。If synchronous I/O is needed, it can be enabled by configuring the AllowSynchronousIO option on the server being used (when calling ConfigureKestrel, for example, if using Kestrel). 請注意,伺服器 (Kestrel、HttpSys、TestServer 等 ) 全部都有自己 AllowSynchronousIO 的選項,而不會影響到其他伺服器。Note that servers (Kestrel, HttpSys, TestServer, etc.) all have their own AllowSynchronousIO option that won't affect other servers. 您可以使用下列選項,以每個要求為基礎來啟用所有伺服器的同步 i/o IHttpBodyControlFeature.AllowSynchronousIOSynchronous I/O can be enabled for all servers on a per-request basis using the IHttpBodyControlFeature.AllowSynchronousIO option:

var syncIOFeature = HttpContext.Features.Get<IHttpBodyControlFeature>();

if (syncIOFeature != null)
{
    syncIOFeature.AllowSynchronousIO = true;
}

如果您對於 TextWriterDispose中呼叫同步 api 的執行或其他串流有問題,請改為呼叫新的 DisposeAsync api。If you have trouble with TextWriter implementations or other streams that call synchronous APIs in Dispose, call the new DisposeAsync API instead.

如需詳細資訊,請參閱 所有伺服器中的 [公告] AllowSynchronousIO 已停用 (dotnet/AspNetCore #7644) For more information, see [Announcement] AllowSynchronousIO disabled in all servers (dotnet/AspNetCore #7644).

輸出格式器緩衝Output formatter buffering

Newtonsoft.JsonXmlSerializer 和基礎的輸出格式器 DataContractSerializer 只支援同步序列化。Newtonsoft.Json, XmlSerializer, and DataContractSerializer based output formatters only support synchronous serialization. 為了讓這些格式器可以使用伺服器的 AllowSynchronousIO 限制,MVC 會在寫入磁片之前緩衝處理這些格式器的輸出。To allow these formatters to work with the AllowSynchronousIO restrictions of the server, MVC buffers the output of these formatters before writing to disk. 由於緩衝處理的結果,MVC 會在使用這些格式器回應時包含 Content-type 標頭。As a result of buffering, MVC will include the Content-Length header when responding using these formatters.

System.Text.Json 支援非同步序列化,因此格式的格式器不 System.Text.Json 會緩衝。System.Text.Json supports asynchronous serialization and consequently the System.Text.Json based formatter does not buffer. 請考慮使用此格式器以改善效能。Consider using this formatter for improved performance.

若要停用緩衝,應用程式可以 SuppressOutputFormatterBuffering 在啟動時設定:To disable buffering, applications can configure SuppressOutputFormatterBuffering in their startup:

services.AddControllers(options => options.SuppressOutputFormatterBuffering = true)

請注意,如果尚未設定,這可能會導致應用程式擲回執行時間例外狀況 AllowSynchronousIONote that this may result in the application throwing a runtime exception if AllowSynchronousIO isn't also configured.

已移除 AspNetCore Kestrel. Https 元件Microsoft.AspNetCore.Server.Kestrel.Https assembly removed

在 ASP.NET Core 2.1 中, Microsoft.AspNetCore.Server.Kestrel.Https.dll 的內容已移至 Microsoft.AspNetCore.Server.Kestrel.Core.dllIn ASP.NET Core 2.1, the contents of Microsoft.AspNetCore.Server.Kestrel.Https.dll were moved to Microsoft.AspNetCore.Server.Kestrel.Core.dll. 這是使用屬性的非重大更新 TypeForwardedToThis was a non-breaking update using TypeForwardedTo attributes. 若為3.0,則會移除空白 Microsoft.AspNetCore.Server.Kestrel.Https.dll 元件和 NuGet 套件。For 3.0, the empty Microsoft.AspNetCore.Server.Kestrel.Https.dll assembly and the NuGet package have been removed.

參考 AspNetCore 的程式庫應該將 ASP.NET Core 相依性更新為2.1 或更新版本。Libraries referencing Microsoft.AspNetCore.Server.Kestrel.Https should update ASP.NET Core dependencies to 2.1 or later.

以 ASP.NET Core 2.1 或更新版本為目標的應用程式和程式庫應移除 Kestrel 的任何直接參考 AspNetCoreApps and libraries targeting ASP.NET Core 2.1 or later should remove any direct references to the Microsoft.AspNetCore.Server.Kestrel.Https package.

Newtonsoft.Js(Json.NET) 支援Newtonsoft.Json (Json.NET) support

改善 ASP.NET Core 共用架構的工作中, Newtonsoft.Js(Json.NET) 已經從 ASP.NET Core 共用架構中移除。As part of the work to improve the ASP.NET Core shared framework, Newtonsoft.Json (Json.NET) has been removed from the ASP.NET Core shared framework.

ASP.NET Core 的預設 JSON 序列化程式現在是 System.Text.Json .Net Core 3.0 中的新功能。The default JSON serializer for ASP.NET Core is now System.Text.Json, which is new in .NET Core 3.0. 盡可能考慮使用 System.Text.JsonConsider using System.Text.Json when possible. 它是高效能,不需要額外的程式庫相依性。It's high-performance and doesn't require an additional library dependency. 不過,由於 System.Text.Json 是新的,因此目前可能遺失您的應用程式所需的功能。However, since System.Text.Json is new, it might currently be missing features that your app needs. 如需詳細資訊,請參閱 如何從 Newtonsoft.Js移至 System.Text.JsFor more information, see How to migrate from Newtonsoft.Json to System.Text.Json.

在 ASP.NET Core 3.0 專案中使用 Newtonsoft.Json SignalRUse Newtonsoft.Json in an ASP.NET Core 3.0 SignalR project

  • 安裝 AspNetCore。 SignalR>microsoft.aspnetcore.mvc.newtonsoftjson NuGet 套件。Install the Microsoft.AspNetCore.SignalR.Protocols.NewtonsoftJson NuGet package.

  • 在用戶端上,將 AddNewtonsoftJsonProtocol 方法呼叫連結至 HubConnectionBuilder 實例:On the client, chain an AddNewtonsoftJsonProtocol method call to the HubConnectionBuilder instance:

    new HubConnectionBuilder()
        .WithUrl("/chathub")
        .AddNewtonsoftJsonProtocol(...)
        .Build();
    
  • 在伺服器上,將 AddNewtonsoftJsonProtocol 方法呼叫連結至 AddSignalR 中的方法呼叫 Startup.ConfigureServicesOn the server, chain an AddNewtonsoftJsonProtocol method call to the AddSignalR method call in Startup.ConfigureServices:

    services.AddSignalR()
        .AddNewtonsoftJsonProtocol(...);
    

在 ASP.NET Core 3.0 MVC 專案中使用 Newtonsoft.JsonUse Newtonsoft.Json in an ASP.NET Core 3.0 MVC project

如需詳細資訊,請參閱 新增 Newtonsoft.Js的 JSON 格式支援For more information, see Add Newtonsoft.Json-based JSON format support.

MVC 服務註冊MVC service registration

ASP.NET Core 3.0 新增了在內部註冊 MVC 案例的新選項 Startup.ConfigureServicesASP.NET Core 3.0 adds new options for registering MVC scenarios inside Startup.ConfigureServices.

有三個與 MVC 案例相關的最新高階擴充方法 IServiceCollection 可供使用。Three new top-level extension methods related to MVC scenarios on IServiceCollection are available. 範本會使用這些新的方法,而不是 AddMvcTemplates use these new methods instead of AddMvc. 不過, AddMvc 其行為會與先前版本中的行為相同。However, AddMvc continues to behave as it has in previous releases.

下列範例會新增控制器和 API 相關功能的支援,但不支援視圖或頁面。The following example adds support for controllers and API-related features, but not views or pages. API 範本會使用下列程式碼:The API template uses this code:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
}

下列範例會新增控制器、API 相關功能和視圖的支援,但不支援頁面。The following example adds support for controllers, API-related features, and views, but not pages. Web 應用程式 (MVC) 範本會使用下列程式碼:The Web Application (MVC) template uses this code:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
}

下列範例會新增頁面的支援 Razor ,以及最基本的控制器支援。The following example adds support for Razor Pages and minimal controller support. Web 應用程式範本會使用下列程式碼:The Web Application template uses this code:

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
}

您也可以結合新的方法。The new methods can also be combined. 下列範例相當於 AddMvc 在 ASP.NET Core 2.2 中呼叫:The following example is equivalent to calling AddMvc in ASP.NET Core 2.2:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    services.AddRazorPages();
}

路由啟動程式碼Routing startup code

如果應用程式呼叫 UseMvcUseSignalR ,可能的話,請將應用程式遷移至 端點路由If an app calls UseMvc or UseSignalR, migrate the app to Endpoint Routing if possible. 為了改進與舊版 MVC 的端點路由相容性,我們已還原 ASP.NET Core 2.2 中引進的 URL 產生變更。To improve Endpoint Routing compatibility with previous versions of MVC, we've reverted some of the changes in URL generation introduced in ASP.NET Core 2.2. 如果您在2.2 中使用端點路由時遇到問題,ASP.NET Core 3.0 中的增強功能,但有下列例外狀況:If you experienced problems using Endpoint Routing in 2.2, expect improvements in ASP.NET Core 3.0 with the following exceptions:

  • 如果應用程式在 IRouter 中執行或繼承 Route ,請使用 DynamicRouteValuesTransformer 做為取代。If the app implements IRouter or inherits from Route, use DynamicRouteValuesTransformer as the replacement.
  • 如果應用程式直接在 RouteData.Routers MVC 內部存取來剖析 url,您可以使用 LinkParser. ParsePathByEndpointName取代此項。If the app directly accesses RouteData.Routers inside MVC to parse URLs, you can replace this with use of LinkParser.ParsePathByEndpointName.
    • 使用路由名稱定義路由。Define the route with a route name.
    • 使用 LinkParser.ParsePathByEndpointName ,並傳入所需的路由名稱。Use LinkParser.ParsePathByEndpointName and pass in the desired route name.

端點路由支援與相同的路由模式語法和路由模式撰寫功能 IRouterEndpoint Routing supports the same route pattern syntax and route pattern authoring features as IRouter. 端點路由支援 IRouteConstraintEndpoint Routing supports IRouteConstraint. 端點路由支援 [Route][HttpGet] 和其他 MVC 路由屬性。Endpoint routing supports [Route], [HttpGet], and the other MVC routing attributes.

針對大部分的應用程式,只 Startup 需要變更。For most applications, only Startup requires changes.

遷移 Startup.Configu) Migrate Startup.Configure

一般建議:General advice:

  • 加入 UseRoutingAdd UseRouting.

  • 如果應用程式呼叫 UseStaticFiles ,請 UseStaticFiles 在之前放置 UseRoutingIf the app calls UseStaticFiles, place UseStaticFiles before UseRouting.

  • 如果應用程式使用驗證/授權功能(例如 AuthorizePage[Authorize] ),請在下列位置呼叫 UseAuthentication and UseAuthorizationafterUseRouting and。 UseCors UseEndpointsIf the app uses authentication/authorization features such as AuthorizePage or [Authorize], place the call to UseAuthentication and UseAuthorization: after, UseRouting and UseCors, but before UseEndpoints:

    public void Configure(IApplicationBuilder app)
    {
      ...
    
      app.UseStaticFiles();
    
      app.UseRouting();
      app.UseCors();
    
      app.UseAuthentication();
      app.UseAuthorization();
    
      app.UseEndpoints(endpoints => {
         endpoints.MapControllers();
      });
    
  • UseMvc 或取代 UseSignalRUseEndpointsReplace UseMvc or UseSignalR with UseEndpoints.

  • 如果應用程式使用 cors 案例(例如),請在 [EnableCors] UseCors 使用 cors 的任何其他中介軟體之前放置呼叫 (例如, UseCorsUseAuthenticationUseAuthorization 和) 之前放置 UseEndpointsIf the app uses CORS scenarios, such as [EnableCors], place the call to UseCors before any other middleware that use CORS (for example, place UseCors before UseAuthentication, UseAuthorization, and UseEndpoints).

  • 將取代為 IHostingEnvironment IWebHostEnvironment ,並加入 using Microsoft.Extensions.Hosting 命名空間的語句。Replace IHostingEnvironment with IWebHostEnvironment and add a using statement for the Microsoft.Extensions.Hosting namespace.

  • 取代 IApplicationLifetimeIHostApplicationLifetime (Microsoft.Extensions.Hosting 命名空間) 。Replace IApplicationLifetime with IHostApplicationLifetime (Microsoft.Extensions.Hosting namespace).

  • 取代 EnvironmentNameEnvironments (Microsoft.Extensions.Hosting 命名空間) 。Replace EnvironmentName with Environments (Microsoft.Extensions.Hosting namespace).

下列程式碼是 Startup.Configure 典型 ASP.NET Core 2.2 應用程式中的範例:The following code is an example of Startup.Configure in a typical ASP.NET Core 2.2 app:

public void Configure(IApplicationBuilder app)
{
    ...

    app.UseStaticFiles();

    app.UseAuthentication();

    app.UseSignalR(hubs =>
    {
        hubs.MapHub<ChatHub>("/chat");
    });

    app.UseMvc(routes =>
    {
        routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
    });
}

更新先前的程式 Startup.Configure 代碼之後:After updating the previous Startup.Configure code:

public void Configure(IApplicationBuilder app)
{
    ...

    app.UseStaticFiles();

    app.UseRouting();

    app.UseCors();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapHub<ChatHub>("/chat");
        endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
    });
}

警告

對於大部分的應用程式,呼叫 UseAuthentication 、和 UseAuthorization UseCors 必須在的呼叫與之間出現,才能 UseRouting UseEndpoints 生效。For most apps, calls to UseAuthentication, UseAuthorization, and UseCors must appear between the calls to UseRouting and UseEndpoints to be effective.

健康情況檢查Health Checks

健康情況檢查會使用端點路由搭配一般主機。Health Checks use endpoint routing with the Generic Host. 在中 Startup.ConfigureMapHealthChecks 使用端點 URL 或相對路徑呼叫端點產生器:In Startup.Configure, call MapHealthChecks on the endpoint builder with the endpoint URL or relative path:

app.UseEndpoints(endpoints =>
{
    endpoints.MapHealthChecks("/health");
});

健康情況檢查端點可以:Health Checks endpoints can:

  • 指定一或多個允許的主機/埠。Specify one or more permitted hosts/ports.
  • 需要授權。Require authorization.
  • 需要 CORS。Require CORS.

如需詳細資訊,請參閱ASP.NET Core 中的健康狀態檢查For more information, see ASP.NET Core 中的健康狀態檢查.

安全性中介軟體指引Security middleware guidance

對授權和 CORS 的支援是與 中介軟體 方法整合的。Support for authorization and CORS is unified around the middleware approach. 這可讓您在這些案例中使用相同的中介軟體和功能。This allows use of the same middleware and functionality across these scenarios. 此版本提供了更新的授權中介軟體,並增強了 CORS 中介軟體,讓它能夠瞭解 MVC 控制器所使用的屬性。An updated authorization middleware is provided in this release, and CORS Middleware is enhanced so that it can understand the attributes used by MVC controllers.

CORSCORS

先前,CORS 可能很難設定。Previously, CORS could be difficult to configure. 已提供中介軟體以用於某些使用案例,但 MVC 篩選準則的用途是在其他使用案例中, 而不 使用中介軟體。Middleware was provided for use in some use cases, but MVC filters were intended to be used without the middleware in other use cases. 在 ASP.NET Core 3.0 中,我們建議所有需要 CORS 的應用程式都使用 CORS 中介軟體搭配端點路由。With ASP.NET Core 3.0, we recommend that all apps that require CORS use the CORS Middleware in tandem with Endpoint Routing. UseCors 可以使用預設原則來提供,而且 [EnableCors][DisableCors] 屬性可用來覆寫預設原則(必要時)。UseCors can be provided with a default policy, and [EnableCors] and [DisableCors] attributes can be used to override the default policy where required.

在下例中︰In the following example:

  • 已針對具有命名原則的所有端點啟用 CORS defaultCORS is enabled for all endpoints with the default named policy.
  • MyController類別會使用屬性來停用 CORS [DisableCors]The MyController class disables CORS with the [DisableCors] attribute.
public void Configure(IApplicationBuilder app)
{
    ...

    app.UseRouting();

    app.UseCors("default");

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapDefaultControllerRoute();
    });
}

[DisableCors]
public class MyController : ControllerBase
{
    ...
}

授權Authorization

在舊版 ASP.NET Core 中,授權支援是透過 [Authorize] 屬性提供。In earlier versions of ASP.NET Core, authorization support was provided via the [Authorize] attribute. 未提供授權中介軟體。Authorization middleware wasn't available. 在 ASP.NET Core 3.0 中,需要授權中介軟體。In ASP.NET Core 3.0, authorization middleware is required. 建議您立即將 ASP.NET Core 授權中介軟體 (UseAuthorization) UseAuthenticationWe recommend placing the ASP.NET Core Authorization Middleware (UseAuthorization) immediately after UseAuthentication. 授權中介軟體也可以使用可覆寫的預設原則進行設定。The Authorization Middleware can also be configured with a default policy, which can be overridden.

在 ASP.NET Core 3.0 或更新版本中, UseAuthorization 會在中呼叫, Startup.Configure 而下列程式 HomeController 要求已登入的使用者:In ASP.NET Core 3.0 or later, UseAuthorization is called in Startup.Configure, and the following HomeController requires a signed in user:

public void Configure(IApplicationBuilder app)
{
    ...

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapDefaultControllerRoute();
    });
}

public class HomeController : Controller
{
    [Authorize]
    public IActionResult BuyWidgets()
    {
        ...
    }
}

使用端點路由時,建議您不要設定 <xref:Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter> ,而改為依賴授權中介軟體。When using endpoint routing, we recommend against configuring <xref:Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter> and instead relying on the Authorization middleware. 如果應用程式 AuthorizeFilter 在 MVC 中使用做為全域篩選,我們建議您重構程式碼,以在的呼叫中提供原則 AddAuthorizationIf the app uses an AuthorizeFilter as a global filter in MVC, we recommend refactoring the code to provide a policy in the call to AddAuthorization.

DefaultPolicy最初設定為需要驗證,因此不需要進行其他設定。The DefaultPolicy is initially configured to require authentication, so no additional configuration is required. 在下列範例中,MVC 端點會標示為, RequireAuthorization 讓所有要求都必須根據來授權 DefaultPolicyIn the following example, MVC endpoints are marked as RequireAuthorization so that all requests must be authorized based on the DefaultPolicy. 不過,在 HomeController 不使用使用者登入應用程式的情況下允許存取,原因 [AllowAnonymous] 如下:However, the HomeController allows access without the user signing into the app due to [AllowAnonymous]:

public void Configure(IApplicationBuilder app)
{
    ...

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapDefaultControllerRoute().RequireAuthorization();
    });
}

[AllowAnonymous]
public class HomeController : Controller
{
    ...
}

特定端點的授權Authorization for specific endpoints

您也可以針對特定的端點類別設定授權。Authorization can also be configured for specific classes of endpoints. 下列程式碼範例會將設定為全域的 MVC 應用程式轉換 AuthorizeFilter 為具有需要授權之特定原則的應用程式:The following code is an example of converting an MVC app that configured a global AuthorizeFilter to an app with a specific policy requiring authorization:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    static readonly string _RequireAuthenticatedUserPolicy = 
                            "RequireAuthenticatedUserPolicy";
    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        services.AddDefaultIdentity<IdentityUser>(
                 options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores<ApplicationDbContext>();

        // Pre 3.0:
        // services.AddMvc(options => options.Filters.Add(new AuthorizeFilter(...));

        services.AddControllersWithViews();
        services.AddRazorPages();
        services.AddAuthorization(o => o.AddPolicy(_RequireAuthenticatedUserPolicy,
                        builder => builder.RequireAuthenticatedUser()));

    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute()
                .RequireAuthorization(_RequireAuthenticatedUserPolicy);
            endpoints.MapRazorPages();
        });
    }
}

也可以自訂原則。Policies can also be customized. DefaultPolicy設定為需要驗證:The DefaultPolicy is configured to require authentication:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        services.AddDefaultIdentity<IdentityUser>(
                 options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores<ApplicationDbContext>();

        services.AddControllersWithViews();
        services.AddRazorPages();
        services.AddAuthorization(options =>
        {
            options.DefaultPolicy = new AuthorizationPolicyBuilder()
              .RequireAuthenticatedUser()
              .Build();
        });

    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute().RequireAuthorization();
            endpoints.MapRazorPages();
        });
    }
}
[AllowAnonymous]
public class HomeController : Controller
{

或者,所有端點都可以設定為要求授權,而不需要 [Authorize] 或藉 RequireAuthorization 由設定 FallbackPolicyAlternatively, all endpoints can be configured to require authorization without [Authorize] or RequireAuthorization by configuring a FallbackPolicy. FallbackPolicy 不同 DefaultPolicyThe FallbackPolicy is different from the DefaultPolicy. DefaultPolicy是由或觸發 [Authorize] RequireAuthorization ,而 FallbackPolicy 當沒有設定其他原則時,就會觸發。The DefaultPolicy is triggered by [Authorize] or RequireAuthorization, while the FallbackPolicy is triggered when no other policy is set. FallbackPolicy 最初是設定為允許不具授權的要求。FallbackPolicy is initially configured to allow requests without authorization.

下列範例與上述範例相同,但會 DefaultPolicy 使用在 FallbackPolicy 所有端點上一律需要驗證,但指定時除外 [AllowAnonymous]The following example is the same as the preceding DefaultPolicy example but uses the FallbackPolicy to always require authentication on all endpoints except when [AllowAnonymous] is specified:

public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddAuthorization(options =>
    {
        options.FallbackPolicy = new AuthorizationPolicyBuilder()
          .RequireAuthenticatedUser()
          .Build();
    });
}

public void Configure(IApplicationBuilder app)
{
    ...

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapDefaultControllerRoute();
    });
}

[AllowAnonymous]
public class HomeController : Controller
{
    ...
}

依中介軟體授權的運作方式,不需具備任何特定授權知識的架構。Authorization by middleware works without the framework having any specific knowledge of authorization. 例如, 健康情況檢查 沒有授權的特定知識,但健康狀態檢查可以有中介軟體所套用的可設定授權原則。For instance, health checks has no specific knowledge of authorization, but health checks can have a configurable authorization policy applied by the middleware.

此外,每個端點都可以自訂其授權需求。Additionally, each endpoint can customize its authorization requirements. 在下列範例中,會 UseAuthorization 使用來處理授權 DefaultPolicy ,但 /healthz 健康情況檢查端點需要 admin 使用者:In the following example, UseAuthorization processes authorization with the DefaultPolicy, but the /healthz health check endpoint requires an admin user:

public void Configure(IApplicationBuilder app)
{
    ...

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints
            .MapHealthChecks("/healthz")
            .RequireAuthorization(new AuthorizeAttribute(){ Roles = "admin", });
    });
}

在某些情況下會執行保護。Protection is implemented for some scenarios. 如果因為缺少中介軟體而略過授權或 CORS 原則時,端點中介軟體會擲回例外狀況。Endpoints Middleware throws an exception if an authorization or CORS policy is skipped due to missing middleware. 分析器支援,以提供有關設定錯誤的其他意見反應。Analyzer support to provide additional feedback about misconfiguration is in progress.

自訂授權處理常式Custom authorization handlers

如果應用程式使用自訂 授權處理常式,則端點路由會將不同的資源類型傳遞給處理常式,而不是 MVC。If the app uses custom authorization handlers, endpoint routing passes a different resource type to handlers than MVC. 預期授權處理常式內容資源屬於 AuthorizationFilterContext (MVC 篩選器所提供 之資源類型的處理常式) 將需要更新,以處理 RouteEndpoint 由端點路由) 提供給授權處理常式的資源類型 (類型的資源。Handlers that expect the authorization handler context resource to be of type AuthorizationFilterContext (the resource type provided by MVC filters) will need to be updated to handle resources of type RouteEndpoint (the resource type given to authorization handlers by endpoint routing).

MVC 仍 AuthorizationFilterContext 會使用資源,因此,如果應用程式使用 MVC 授權篩選和端點路由授權,則可能需要處理這兩種類型的資源。MVC still uses AuthorizationFilterContext resources, so if the app uses MVC authorization filters along with endpoint routing authorization, it may be necessary to handle both types of resources.

SignalR

中樞的對應 SignalR 現在會在內部進行 UseEndpointsMapping of SignalR hubs now takes place inside UseEndpoints.

使用對應每個中樞 MapHubMap each hub with MapHub. 如同先前的版本,每個中樞都已明確列出。As in previous versions, each hub is explicitly listed.

在下列範例中, ChatHub SignalR 會新增中樞的支援:In the following example, support for the ChatHub SignalR hub is added:

public void Configure(IApplicationBuilder app)
{
    ...

    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapHub<ChatHub>();
    });
}

有一個新的選項,可控制用戶端的訊息大小限制。There is a new option for controlling message size limits from clients. 例如,在 Startup.ConfigureServices 中:For example, in Startup.ConfigureServices:

services.AddSignalR(hubOptions =>
{
    hubOptions.MaximumReceiveMessageSize = 32768;
});

在 ASP.NET Core 2.2 中,您可以設定 TransportMaxBufferSize 和,以有效地控制訊息大小上限。In ASP.NET Core 2.2, you could set the TransportMaxBufferSize and that would effectively control the maximum message size. 在 ASP.NET Core 3.0 中,該選項現在只會控制觀察到背壓之前的大小上限。In ASP.NET Core 3.0, that option now only controls the maximum size before backpressure is observed.

MVC 控制器MVC controllers

控制器的對應現在會在內部進行 UseEndpointsMapping of controllers now takes place inside UseEndpoints.

MapControllers如果應用程式使用屬性路由,請新增。Add MapControllers if the app uses attribute routing. 因為路由包含 ASP.NET Core 3.0 或更新版本中許多架構的支援,所以新增屬性路由控制器是加入宣告的。Since routing includes support for many frameworks in ASP.NET Core 3.0 or later, adding attribute-routed controllers is opt-in.

取代下列項目:Replace the following:

  • MapControllerRouteMapRouteMapRoute with MapControllerRoute
  • MapAreaControllerRouteMapAreaRouteMapAreaRoute with MapAreaControllerRoute

由於路由現在支援的不只是 MVC,因此術語已經改變,讓這些方法清楚陳述它們的用途。Since routing now includes support for more than just MVC, the terminology has changed to make these methods clearly state what they do. 慣例路由(例如) MapControllerRoute / MapAreaControllerRoute / MapDefaultControllerRoute 會依其新增的順序套用。Conventional routes such as MapControllerRoute/MapAreaControllerRoute/MapDefaultControllerRoute are applied in the order that they're added. (放置更明確的路由,例如區域) 的路由。Place more specific routes (such as routes for an area) first.

在下例中︰In the following example:

  • MapControllers 新增屬性路由控制器的支援。MapControllers adds support for attribute-routed controllers.
  • MapAreaControllerRoute 在區域中新增控制器的傳統路由。MapAreaControllerRoute adds a conventional route for controllers in an area.
  • MapControllerRoute 新增控制器的一般路由。MapControllerRoute adds a conventional route for controllers.
public void Configure(IApplicationBuilder app)
{
    ...

    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapAreaControllerRoute(
            "admin",
            "admin",
            "Admin/{controller=Home}/{action=Index}/{id?}");
        endpoints.MapControllerRoute(
            "default", "{controller=Home}/{action=Index}/{id?}");
    });
}

從控制器動作名稱移除非同步尾碼Async suffix removal from controller action names

在 ASP.NET Core 3.0 中,ASP.NET Core MVC 會 Async 從控制器動作名稱移除尾碼。In ASP.NET Core 3.0, ASP.NET Core MVC removes the Async suffix from controller action names. 路由和連結產生都會受到這個新的預設值所影響。Both routing and link generation are impacted by this new default. 例如:For example:

public class ProductsController : Controller
{
    public async Task<IActionResult> ListAsync()
    {
        var model = await _dbContext.Products.ToListAsync();
        return View(model);
    }
}

在 ASP.NET Core 3.0 之前:Prior to ASP.NET Core 3.0:

  • 您可以在 Products/metrics.listasync route 存取上述動作。The preceding action could be accessed at the Products/ListAsync route.

  • 需要指定尾碼的連結產生 AsyncLink generation required specifying the Async suffix. 例如:For example:

    <a asp-controller="Products" asp-action="ListAsync">List</a>
    

在 ASP.NET Core 3.0:In ASP.NET Core 3.0:

  • 您可以在 Products/List route 存取上述動作。The preceding action can be accessed at the Products/List route.

  • 連結產生不需要指定 Async 尾碼。Link generation doesn't require specifying the Async suffix. 例如:For example:

    <a asp-controller="Products" asp-action="List">List</a>
    

此變更不會影響使用屬性指定的名稱 [ActionName]This change doesn't affect names specified using the [ActionName] attribute. 您可以使用中的下列程式碼來停用預設行為 Startup.ConfigureServicesThe default behavior can be disabled with the following code in Startup.ConfigureServices:

services.AddMvc(options =>
    options.SuppressAsyncSuffixInActionNames = false);

如同 舊版路由的差異檔中所述,使用和類似的 api (連結產生有一些差異 Url.Link ,例如) 。As explained in documentation on differences from earlier versions of routing, there are some differences in link generation (using Url.Link and similar APIs, for example). 其中包括:These include:

  • 根據預設,使用端點路由時,不一定會保留所產生之 Uri 中的路由參數大小寫。By default, when using endpoint routing, casing of route parameters in generated URIs is not necessarily preserved. 此行為可以使用介面來控制 IOutboundParameterTransformerThis behavior can be controlled with the IOutboundParameterTransformer interface.
  • 產生無效路由的 URI (控制器/動作或不存在的頁面) 將會在端點路由下產生空字串,而不是產生不正確 URI。Generating a URI for an invalid route (a controller/action or page that doesn't exist) will produce an empty string under endpoint routing instead of producing an invalid URI.
  • 從目前內容 (路由參數的環境值,不會在與端點路由的連結產生中自動使用) 。Ambient values (route parameters from the current context) are not automatically used in link generation with endpoint routing. 先前,當 (或頁面) 產生另一個動作的連結時,會從 目前 的路由環境值推斷未指定的路由值。Previously, when generating a link to another action (or page), unspecified route values would be inferred from the current routes ambient values. 使用端點路由時,必須在連結產生期間明確指定所有路由參數。When using endpoint routing, all route parameters must be specified explicitly during link generation.

Razor 頁面Razor Pages

對應 Razor 頁面現在會在內部進行 UseEndpointsMapping Razor Pages now takes place inside UseEndpoints.

MapRazorPages如果應用程式使用頁面,請新增 Razor 。Add MapRazorPages if the app uses Razor Pages. 由於端點路由包含許多架構的支援, Razor 現在加入頁面是加入宣告的。Since Endpoint Routing includes support for many frameworks, adding Razor Pages is now opt-in.

在下列 Startup.Configure 方法中, MapRazorPages 新增了頁面的支援 Razor :In the following Startup.Configure method, MapRazorPages adds support for Razor Pages:

public void Configure(IApplicationBuilder app)
{
    ...

    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
    });
}

使用不含端點路由的 MVCUse MVC without Endpoint Routing

UseMvc ASP.NET Core 3.0 中透過或使用 MVC UseMvcWithDefaultRoute 時,需要明確加入 Startup.ConfigureServicesUsing MVC via UseMvc or UseMvcWithDefaultRoute in ASP.NET Core 3.0 requires an explicit opt-in inside Startup.ConfigureServices. 這是必要的,因為 MVC 必須知道它是否可以在初始化期間依賴授權和 CORS 中介軟體。This is required because MVC must know whether it can rely on the authorization and CORS Middleware during initialization. 如果應用程式嘗試使用不支援的設定,則會提供分析器來發出警告。An analyzer is provided that warns if the app attempts to use an unsupported configuration.

如果應用程式需要舊版 IRouter 支援,請 EnableEndpointRouting 在中使用下列任何一種方法來停用 Startup.ConfigureServicesIf the app requires legacy IRouter support, disable EnableEndpointRouting using any of the following approaches in Startup.ConfigureServices:

services.AddMvc(options => options.EnableEndpointRouting = false);
services.AddControllers(options => options.EnableEndpointRouting = false);
services.AddControllersWithViews(options => options.EnableEndpointRouting = false);
services.AddRazorPages().AddMvcOptions(options => options.EnableEndpointRouting = false);

健康狀態檢查Health checks

健康情況檢查可以用來做為具有端點路由的 路由器Health checks can be used as a router-ware with Endpoint Routing.

新增 MapHealthChecks 以搭配端點路由使用健康情況檢查。Add MapHealthChecks to use health checks with Endpoint Routing. MapHealthChecks方法會接受類似的自 UseHealthChecks 變數。The MapHealthChecks method accepts arguments similar to UseHealthChecks. 使用 over 的優點 MapHealthChecks UseHealthChecks 是能夠套用授權,並對比對原則有更精細的控制。The advantage of using MapHealthChecks over UseHealthChecks is the ability to apply authorization and to have greater fine-grained control over the matching policy.

在下列範例中, MapHealthChecks 會針對的健康狀態檢查端點呼叫 /healthzIn the following example, MapHealthChecks is called for a health check endpoint at /healthz:

public void Configure(IApplicationBuilder app)
{
    ...

    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapHealthChecks("/healthz", new HealthCheckOptions() { });
    });
}

HostBuilder 取代 >webhostbuilderHostBuilder replaces WebHostBuilder

ASP.NET Core 3.0 範本使用 一般主機The ASP.NET Core 3.0 templates use Generic Host. 舊版使用的 Web 主機Previous versions used Web Host. 下列程式碼顯示 ASP.NET Core 3.0 範本產生的 Program 類別:The following code shows the ASP.NET Core 3.0 template generated Program class:

// requires using Microsoft.AspNetCore.Hosting;
// requires using Microsoft.Extensions.Hosting;

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

下列程式碼顯示 ASP.NET Core 2.2 範本產生的 Program 類別:The following code shows the ASP.NET Core 2.2 template-generated Program class:

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

IWebHostBuilder 會保留在3.0 中,而且是在 webBuilder 上述程式碼範例中所見的型別。IWebHostBuilder remains in 3.0 and is the type of the webBuilder seen in the preceding code sample. WebHostBuilder 將在未來的版本中被取代,並取代為 HostBuilderWebHostBuilder will be deprecated in a future release and replaced by HostBuilder.

從到相依性 WebHostBuilder HostBuilder 插入 (DI) 最重要的變更。The most significant change from WebHostBuilder to HostBuilder is in dependency injection (DI). 使用時 HostBuilder ,您只能將下列程式插入至 Startup 的函式:When using HostBuilder, you can only inject the following into Startup's constructor:

HostBuilderDI 條件約束:The HostBuilder DI constraints:

  • 讓 DI 容器只建立一次。Enable the DI container to be built only one time.
  • 避免產生的物件存留期問題,例如解決多個 singleton 的實例。Avoids the resulting object lifetime issues like resolving multiple instances of singletons.

如需詳細資訊,請參閱 避免 ASP.NET Core 3 中的啟動服務插入For more information, see Avoiding Startup service injection in ASP.NET Core 3.

AddAuthorization 移至不同的元件AddAuthorization moved to a different assembly

Microsoft.AspNetCore.Authorization.dll中的 ASP.NET Core 2.2 和較低的 AddAuthorization 方法: Microsoft.AspNetCore.Authorization.dllThe ASP.NET Core 2.2 and lower AddAuthorization methods in Microsoft.AspNetCore.Authorization.dll:

  • 已重新命名 AddAuthorizationCoreHave been renamed AddAuthorizationCore.
  • 已移至 Microsoft.AspNetCore.Authorization.Policy.dllHave been moved to Microsoft.AspNetCore.Authorization.Policy.dll.

使用 Microsoft.AspNetCore.Authorization.dllMicrosoft.AspNetCore.Authorization.Policy.dll 的應用程式不會受到影響。Apps that are using both Microsoft.AspNetCore.Authorization.dll and Microsoft.AspNetCore.Authorization.Policy.dll aren't impacted.

未使用 Microsoft.AspNetCore.Authorization.Policy.dll 的應用程式應該執行下列其中一項:Apps that are not using Microsoft.AspNetCore.Authorization.Policy.dll should do one of the following:

  • 新增 Microsoft.AspNetCore.Authorization.Policy.dll的參考。Add a reference to Microsoft.AspNetCore.Authorization.Policy.dll. 這種方法適用于大部分的應用程式,而且全部都是必要的。This approach works for most apps and is all that is required.
  • 切換至使用 AddAuthorizationCoreSwitch to using AddAuthorizationCore

如需詳細資訊,請參閱) 多載中 的重大變更 AddAuthorization(o => 存在於不同的元件 #386For more information, see Breaking change in AddAuthorization(o =>) overload lives in a different assembly #386.

Identity UIIdentity UI

Identity ASP.NET Core 3.0 的 UI 更新:Identity UI updates for ASP.NET Core 3.0:

  • 將套件參考新增至 AspNetCore。 IdentityUIAdd a package reference to Microsoft.AspNetCore.Identity.UI.
  • 未使用頁面的應用程式 Razor 必須呼叫 MapRazorPagesApps that don't use Razor Pages must call MapRazorPages. 請參閱本檔中的 Razor 頁面See Razor Pages in this document.
  • 啟動程式4是預設的 UI 架構。Bootstrap 4 is the default UI framework. 設定 IdentityUIFrameworkVersion 專案屬性以變更預設值。Set an IdentityUIFrameworkVersion project property to change the default. 如需詳細資訊,請參閱 此 GitHub 公告For more information, see this GitHub announcement.

SignalR

SignalRJavaScript 用戶端已從變更 @aspnet/signalr@microsoft/signalrThe SignalR JavaScript client has changed from @aspnet/signalr to @microsoft/signalr. 若要回應這項變更,請變更檔案package.jsonrequire 語句和 ECMAScript 語句package.js的參考 importTo react to this change, change the references in package.json files, require statements, and ECMAScript import statements.

System.Text.Json 是預設通訊協定System.Text.Json is the default protocol

System.Text.Json 現在是用戶端和伺服器所使用的預設中樞通訊協定。System.Text.Json is now the default Hub protocol used by both the client and server.

在中 Startup.ConfigureServices ,呼叫 AddJsonProtocol 以設定序列化程式選項。In Startup.ConfigureServices, call AddJsonProtocol to set serializer options.

伺服器:Server:

services.AddSignalR(...)
        .AddJsonProtocol(options =>
        {
            options.PayloadSerializerOptions.WriteIndented = false;
        })

用戶端:Client:

new HubConnectionBuilder()
    .WithUrl("/chathub")
    .AddJsonProtocol(options =>
    {
        options.PayloadSerializerOptions.WriteIndented = false;
    })
    .Build();

切換至 Newtonsoft.Js開啟Switch to Newtonsoft.Json

如果您使用 上的 Newtonsoft.Js的功能 System.Text.Js上不支援,您可以切換回 Newtonsoft.JsonIf you're using features of Newtonsoft.Json that aren't supported in System.Text.Json, you can switch back to Newtonsoft.Json. 請參閱本文稍早 ASP.NET Core 3.0 SignalR 專案中的使用 Newtonsoft.JsSee Use Newtonsoft.Json in an ASP.NET Core 3.0 SignalR project earlier in this article.

Redis 分散式快取Redis distributed caches

ASP.NET Core 3.0 或更新版本的應用程式無法使用 Redis 套件。The Microsoft.Extensions.Caching.Redis package isn't available for ASP.NET Core 3.0 or later apps. 將套件參考取代為 StackExchangeRedisReplace the package reference with Microsoft.Extensions.Caching.StackExchangeRedis. 如需詳細資訊,請參閱ASP.NET Core 中的分散式快取For more information, see ASP.NET Core 中的分散式快取.

加入執行時間編譯Opt in to runtime compilation

在 ASP.NET Core 3.0 之前,views 的執行時間編譯是架構的隱含功能。Prior to ASP.NET Core 3.0, runtime compilation of views was an implicit feature of the framework. 執行時間編譯會補充視圖的組建階段編譯。Runtime compilation supplements build-time compilation of views. 它可讓架構在 Razor 修改檔案時,將視圖和頁面編譯 (的 cshtml 檔案) ,而不需要重建整個應用程式。It allows the framework to compile Razor views and pages (.cshtml files) when the files are modified, without having to rebuild the entire app. 這項功能支援在 IDE 中進行快速編輯,以及重新整理瀏覽器以查看變更的案例。This feature supports the scenario of making a quick edit in the IDE and refreshing the browser to view the changes.

在 ASP.NET Core 3.0 中,執行時間編譯是加入宣告的情節。In ASP.NET Core 3.0, runtime compilation is an opt-in scenario. 組建階段編譯是預設啟用的視圖編譯的唯一機制。Build-time compilation is the only mechanism for view compilation that's enabled by default. 執行時間相依于 Visual Studio Code 中的 Visual Studio 或 dotnet 監看 ,以在偵測到 cshtml 檔案的變更時重建專案。The runtime relies on Visual Studio or dotnet-watch in Visual Studio Code to rebuild the project when it detects changes to .cshtml files. 在 Visual Studio 中,執行專案中的 .cscshtmlRazor 檔案的變更 (Ctrl + F5) ,但是未 (f5) 進行偵錯工具,則會觸發專案的重新編譯。In Visual Studio, changes to .cs, .cshtml, or .razor files in the project being run (Ctrl+F5), but not debugged (F5), trigger recompilation of the project.

若要在您的 ASP.NET Core 3.0 專案中啟用執行時間編譯:To enable runtime compilation in your ASP.NET Core 3.0 project:

  1. 請安裝 AspNetCore Razor 。>microsoft.aspnetcore.mvc.razor.runtimecompilation NuGet 套件。Install the Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation NuGet package.

  2. 更新 Startup.ConfigureServices 以呼叫 AddRazorRuntimeCompilationUpdate Startup.ConfigureServices to call AddRazorRuntimeCompilation:

    針對 ASP.NET Core MVC,請使用下列程式碼:For ASP.NET Core MVC, use the following code:

    services.AddControllersWithViews()
        .AddRazorRuntimeCompilation(...);
    

    針對 ASP.NET Core Razor 頁面,請使用下列程式碼:For ASP.NET Core Razor Pages, use the following code:

    services.AddRazorPages()
        .AddRazorRuntimeCompilation(...);
    

中的範例 https://github.com/aspnet/samples/tree/master/samples/aspnetcore/mvc/runtimecompilation 顯示在開發環境中有條件地啟用執行時間編譯的範例。The sample at https://github.com/aspnet/samples/tree/master/samples/aspnetcore/mvc/runtimecompilation shows an example of enabling runtime compilation conditionally in Development environments.

如需檔案編譯的詳細資訊 Razor ,請參閱 Razor ASP.NET Core 中的檔案編譯For more information on Razor file compilation, see Razor ASP.NET Core 中的檔案編譯.

透過多目標來遷移程式庫Migrate libraries via multi-targeting

程式庫通常需要支援多個版本的 ASP.NET Core。Libraries often need to support multiple versions of ASP.NET Core. 針對舊版 ASP.NET Core 編譯的大部分程式庫都應該繼續運作,而不會發生問題。Most libraries that were compiled against previous versions of ASP.NET Core should continue working without issues. 下列情況需要跨編譯應用程式:The following conditions require the app to be cross-compiled:

  • 程式庫依賴具有二進位 中斷性變更的功能。The library relies on a feature that has a binary breaking change.
  • 程式庫想要利用 ASP.NET Core 3.0 中的新功能。The library wants to take advantage of new features in ASP.NET Core 3.0.

例如:For example:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFrameworks>netcoreapp3.0;netstandard2.0</TargetFrameworks>
  </PropertyGroup>

  <ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp3.0'">
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
  </ItemGroup>

  <ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
    <PackageReference Include="Microsoft.AspNetCore" Version="2.1.0" />
  </ItemGroup>
</Project>

#ifdefs 來啟用 ASP.NET Core 3.0 專用的 api:Use #ifdefs to enable ASP.NET Core 3.0-specific APIs:

var webRootFileProvider =
#if NETCOREAPP3_0
    GetRequiredService<IWebHostEnvironment>().WebRootFileProvider;
#elif NETSTANDARD2_0
    GetRequiredService<IHostingEnvironment>().WebRootFileProvider;
#else
#error unknown target framework
#endif

如需在類別庫中使用 ASP.NET Core Api 的詳細資訊,請參閱 在類別庫中使用 ASP.NET Core ApiFor more information on using ASP.NET Core APIs in a class library, see 在類別庫中使用 ASP.NET Core Api.

其他變更Miscellaneous changes

.NET Core 3.0 和更新版本中的驗證系統會將不可為 null 的參數或系結屬性視為有 [Required] 屬性。The validation system in .NET Core 3.0 and later treats non-nullable parameters or bound properties as if they had a [Required] attribute. 如需詳細資訊,請參閱 [必要] 屬性For more information, see [Required] attribute.

發佈Publish

刪除專案目錄中的 binobj 資料夾。Delete the bin and obj folders in the project directory.

TestServerTestServer

針對 TestServer 直接搭配 泛型主機使用的應用程式,請 TestServer 在中的上建立 IWebHostBuilder ConfigureWebHostFor apps that use TestServer directly with the Generic Host, create the TestServer on an IWebHostBuilder in ConfigureWebHost:

[Fact]
public async Task GenericCreateAndStartHost_GetTestServer()
{
    using var host = await new HostBuilder()
        .ConfigureWebHost(webBuilder =>
        {
            webBuilder
                .UseTestServer()
                .Configure(app => { });
        })
    .StartAsync();

    var response = await host.GetTestServer().CreateClient().GetAsync("/");

    Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}

中斷 API 變更Breaking API changes

檢查重大變更:Review breaking changes:

使用 catch-all 參數的端點路由Endpoint routing with catch-all parameter

警告

Catch-all參數可能會因為路由中的錯誤而不正確地符合路由。A catch-all parameter may match routes incorrectly due to a bug in routing. 受此 bug 影響的應用程式具有下列特性:Apps impacted by this bug have the following characteristics:

  • Catch-all 路由,例如 {**slug}"A catch-all route, for example, {**slug}"
  • Catch-all 路由無法符合它應該符合的要求。The catch-all route fails to match requests it should match.
  • 移除其他路由會讓全部攔截路由開始運作。Removing other routes makes catch-all route start working.

如需遇到此錯誤的範例案例,請參閱 GitHub bug 1867716579See GitHub bugs 18677 and 16579 for example cases that hit this bug.

.Net Core 3.1.301 SDK 和更新版本包含此錯誤的加入宣告修正。An opt-in fix for this bug is contained in .NET Core 3.1.301 SDK and later. 下列程式碼會設定可修正此錯誤的內部參數:The following code sets an internal switch that fixes this bug:

public static void Main(string[] args)
{
   AppContext.SetSwitch("Microsoft.AspNetCore.Routing.UseCorrectCatchAllBehavior", 
                         true);
   CreateHostBuilder(args).Build().Run();
}
// Remaining code removed for brevity.

Azure App Service 上的 .NET Core 3。0.NET Core 3.0 on Azure App Service

將 .NET Core 推出至 Azure App Service 的作業已完成。The rollout of .NET Core to Azure App Service is finished. .NET Core 3.0 適用于所有 Azure App Service 資料中心。.NET Core 3.0 is available in all Azure App Service datacenters.