從 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.

必要條件:Prerequisites

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

如果您的解決方案依賴global json檔案以特定 .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
  • Microsoft.AspNetCore.Authentication.CookiesMicrosoft.AspNetCore.Authentication.Cookies
  • Microsoft.AspNetCore.Authentication.CoreMicrosoft.AspNetCore.Authentication.Core
  • Microsoft.AspNetCore.Authentication.OAuthMicrosoft.AspNetCore.Authentication.OAuth
  • Microsoft.AspNetCore.Authorization.PolicyMicrosoft.AspNetCore.Authorization.Policy
  • Microsoft.AspNetCore.CookiePolicyMicrosoft.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
  • Microsoft.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
  • Microsoft.AspNetCore.Mvc.RazorMicrosoft.AspNetCore.Mvc.Razor
  • Microsoft.AspNetCore.Mvc.Razor.ViewCompilationMicrosoft.AspNetCore.Mvc.Razor.ViewCompilation
  • Microsoft.AspNetCore.Mvc.RazorPagesMicrosoft.AspNetCore.Mvc.RazorPages
  • Microsoft.AspNetCore.Mvc.TagHelpersMicrosoft.AspNetCore.Mvc.TagHelpers
  • Microsoft.AspNetCore.Mvc.ViewFeaturesMicrosoft.AspNetCore.Mvc.ViewFeatures
  • Microsoft.AspNetCore.RazorMicrosoft.AspNetCore.Razor
  • Microsoft.AspNetCore.Razor.RuntimeMicrosoft.AspNetCore.Razor.Runtime
  • Microsoft.AspNetCore.Razor.DesignMicrosoft.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. 標頭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.

  • Microsoft.NET.Sdk.Web SDK 為目標的專案會隱含地參考 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.SdkMicrosoft.NET.Sdk.Razor SDK 為目標的專案,應該將明確的 FrameworkReference 新增至 Microsoft.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

使用相依于 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.json json檔案。To 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.App 套件參考一部分的部分元件。ASP.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 Pages 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 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 Pages 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 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,而這些分析器先前隨附于Microsoft.套件中。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

提供 MVC UI 元件的 Razor 類別庫專案必須設定專案檔中的 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> 屬性的值為 InProcess,您可以選擇性地將它移除。You may optionally remove the <AspNetCoreHostingModel> property in the project file if its value is InProcess.

KestrelKestrel

組態Configuration

將 Kestrel 設定遷移至 ConfigureWebHostDefaultsProgram.cs)所提供的 web 主機產生器:Migrate 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手動建立主機,請在 ConfigureWebHostDefaults的 web 主機產生器上呼叫 UseKestrelIf 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

已從 Kestrel 移除連接介面卡(Microsoft.AspNetCore.Server.Kestrel.Core.Adapter.Internal.IConnectionAdapter)。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.Abstractions中的公用介面。The 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.
  • 已從 KestrelServerOptions移除 Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal.SchedulingModeMicrosoft.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.

這會導致一些關於標頭和結尾的模稜兩可問題,因此結尾已移至 3.0 中的新集合 (RequestTrailerExtensions)。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. 即使此方法傳回 true,也可能沒有尾端可讀取。There 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 再呼叫 GetTrailer,否則如果要求不支援尾端標頭,則可能會發生 NotSupportedExceptionCheck 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 會啟用或停用同步 IO API,例如 HttpRequest.Body.ReadHttpResponse.Body.WriteStream.FlushAllowSynchronousIO enables or disables synchronous IO 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 中,預設會停用 AllowSynchronousIOIn 3.0, AllowSynchronousIO is disabled by default. 如需詳細資訊,請參閱 Kestrel 文章中的同步 IO 一節For more information, see the Synchronous IO section in the Kestrel article.

如果需要同步 IO,可以藉由在使用中的伺服器上設定 AllowSynchronousIO 選項(例如,在呼叫 ConfigureKestrel時)來啟用此功能(例如,如果使用 Kestrel)。If synchronous IO 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. 您可以使用 IHttpBodyControlFeature.AllowSynchronousIO 選項,以每個要求為基礎來啟用所有伺服器的同步 IO:Synchronous IO 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;
}

如果您對 TextWriter 的執行或其他在Dispose中呼叫同步 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).

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

在 ASP.NET Core 2.1 中,AspNetCore 的內容已移至 AspNetCore. Kestrel. Kestrel ... d. d. .dll。In ASP.NET Core 2.1, the contents of Microsoft.AspNetCore.Server.Kestrel.Https.dll were moved to Microsoft.AspNetCore.Server.Kestrel.Core.dll. 這是使用 TypeForwardedTo 屬性的非重大更新。This was a non-breaking update using TypeForwardedTo attributes. 若為 3.0,則已移除空的 AspNetCore Kestrel 和 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的任何直接參考。Apps and libraries targeting ASP.NET Core 2.1 or later should remove any direct references to the Microsoft.AspNetCore.Server.Kestrel.Https package.

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

做為改善 ASP.NET Core 共用架構的一部分,已從 ASP.NET Core 共用架構中移除Newtonsoft (Json.NET)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 遷移至 system.objectFor more information, see How to migrate from Newtonsoft.Json to System.Text.Json.

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

  • 安裝AspNetCore。SignalR。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 方法呼叫連結至 Startup.ConfigureServices中的 AddSignalR 方法呼叫:On the server, chain an AddNewtonsoftJsonProtocol method call to the AddSignalR method call in Startup.ConfigureServices:

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

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

  • 安裝AspNetCore NewtonsoftJson套件。Install the Microsoft.AspNetCore.Mvc.NewtonsoftJson package.

  • 更新 Startup.ConfigureServices 以呼叫 AddNewtonsoftJsonUpdate Startup.ConfigureServices to call AddNewtonsoftJson.

    services.AddMvc()
        .AddNewtonsoftJson();
    

    AddNewtonsoftJson 與新的 MVC 服務註冊方法相容:AddNewtonsoftJson is compatible with the new MVC service registration methods:

    • AddRazorPages
    • AddControllersWithViews
    • AddControllers
    services.AddControllers()
        .AddNewtonsoftJson();
    

    您可以在 AddNewtonsoftJson的呼叫中設定 Newtonsoft.Json 設定:Newtonsoft.Json settings can be set in the call to AddNewtonsoftJson:

    services.AddMvc()
        .AddNewtonsoftJson(options =>
               options.SerializerSettings.ContractResolver =
                  new CamelCasePropertyNamesContractResolver());
    

注意: 如果 AddNewtonsoftJson 方法無法使用,請確定您已安裝AspNetCore NewtonsoftJson套件。Note: If the AddNewtonsoftJson method isn't available, make sure that you installed the Microsoft.AspNetCore.Mvc.NewtonsoftJson package. 常見的錯誤是安裝Newtonsoft Json封裝,而不是AspNetCore NewtonsoftJson套件。A common error is to install the Newtonsoft.Json package instead of the Microsoft.AspNetCore.Mvc.NewtonsoftJson package.

MVC 服務註冊MVC service registration

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

有三個與 IServiceCollection 上 MVC 案例相關的最上層擴充方法。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 相關功能的支援,但不會加入 views 或 pages。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 相關功能和 views 的支援,但不會加入頁面。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 Pages 和最低控制器支援的支援。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. 下列範例相當於呼叫 ASP.NET Core 2.2 中的 AddMvcThe 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.

  • 如果應用程式直接存取 MVC 中的 RouteData.Routers 以剖析 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.

端點路由支援與 IRouter相同的路由模式語法和路由模式撰寫功能。Endpoint 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.

遷移啟動。設定Migrate Startup.Configure

一般建議:General advice:

  • 加入 UseRoutingAdd UseRouting.

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

  • 如果應用程式使用驗證/授權功能(例如 AuthorizePage[Authorize]),請將呼叫放到 UseAuthenticationUseAuthorization: after、UseRoutingUseCors之後,但在 UseEndpoints之前:If 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();
      });
    
  • UseEndpoints取代 UseMvcUseSignalRReplace UseMvc or UseSignalR with UseEndpoints.

  • 如果應用程式使用cors案例(例如 [EnableCors]),請在使用 cors 的任何其他中介軟體之前,先將 UseCors 的呼叫放入(例如,將 UseCors 放在 UseAuthenticationUseAuthorizationUseEndpoints之前)。If 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).

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

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

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

下列程式碼是典型 ASP.NET Core 2.2 應用程式中 Startup.Configure 的範例: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?}");
    });
}

警告

對於大部分的應用程式而言,UseAuthenticationUseAuthorizationUseCors 的呼叫必須出現在 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.Configure中,使用端點 URL 或相對路徑,在端點產生器上呼叫 MapHealthChecksIn 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:

  • 具有 default 名稱為 policy 的所有端點都會啟用 CORS。CORS is enabled for all endpoints with the default named policy.
  • MyController 類別會停用具有 [DisableCors] 屬性的 CORS。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. 建議您在 UseAuthentication之後立即放置 ASP.NET Core 授權中介軟體(UseAuthorization)。We 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 中的全域篩選器,建議您重構程式碼,以在 AddAuthorization的呼叫中提供原則。If 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,以便所有要求都必須根據 DefaultPolicy進行授權。In 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. 下列程式碼範例會將設定全域 AuthorizeFilter 的 MVC 應用程式,轉換為具有需要授權之特定原則的應用程式: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. FallbackPolicyDefaultPolicy不同。The FallbackPolicy is different from the DefaultPolicy. DefaultPolicy 是由 [Authorize]RequireAuthorization觸發,而當未設定其他原則時,則會觸發 FallbackPolicyThe 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 中樞的對應現在會在 UseEndpoints內進行。Mapping 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

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

如果應用程式使用屬性路由,請新增 MapControllersAdd 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路由存取。The preceding action could be accessed at the Products/ListAsync route.

  • 需要指定 Async 尾碼的連結產生。Link 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:

  • 先前的動作可在產品/清單路由存取。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.ConfigureServices中的下列程式碼來停用預設行為:The default behavior can be disabled with the following code in Startup.ConfigureServices:

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

如檔中與舊版路由的差異所述,連結產生有一些差異(例如,使用 Url.Link 和類似的 api)。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. 您可以使用 IOutboundParameterTransformer 介面來控制此行為。This 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 PagesRazor Pages

對應 Razor Pages 現在會在 UseEndpoints內進行。Mapping Razor Pages now takes place inside UseEndpoints.

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

在下列 Startup.Configure 方法中,MapRazorPages 新增 Razor Pages 的支援: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

在 ASP.NET Core 3.0 中使用 MVC via UseMvcUseMvcWithDefaultRoute 需要在 Startup.ConfigureServices內明確加入宣告。Using 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 支援,請使用 Startup.ConfigureServices中的下列任一方法來停用 EnableEndpointRoutingIf 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. UseHealthChecks 上使用 MapHealthChecks 的優點是能夠套用授權並對比對原則進行更精細的控制。The advantage of using MapHealthChecks over UseHealthChecks is the ability to apply authorization and to have greater fine-grained control over the matching policy.

在下列範例中,會針對 /healthz的健康狀態檢查端點呼叫 MapHealthChecksIn 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. 下列程式碼顯示 Program 類別所產生的 ASP.NET Core 3.0 範本: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 將在未來的版本中被取代,並由 HostBuilder取代。WebHostBuilder will be deprecated in a future release and replaced by HostBuilder.

WebHostBuilderHostBuilder 最重大的變更是在相依性插入(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:

HostBuilder DI 條件約束:The HostBuilder DI constraints:

  • 讓 DI 容器只建立一次。Enable the DI container to be built only one time.
  • 避免產生的物件存留期問題,例如解析單次個體的多個實例。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

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

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

同時使用AspNetCore和 AspNetCore 的應用程式不會受到影響。(不受此原則)。Apps that are using both Microsoft.AspNetCore.Authorization.dll and Microsoft.AspNetCore.Authorization.Policy.dll aren't impacted.

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

  • 將參考新增至AspNetCore. Policy .dllAdd 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 =>中的重大變更)多載存在於不同的元件 #386 中For more information, see Breaking change in AddAuthorization(o =>) overload lives in a different assembly #386.

身分識別 UIIdentity UI

ASP.NET Core 3.0 的身分識別 UI 更新:Identity UI updates for ASP.NET Core 3.0:

  • 將套件參考新增至AspNetCoreAdd a package reference to Microsoft.AspNetCore.Identity.UI.
  • 不使用 Razor Pages 的應用程式必須呼叫 MapRazorPagesApps that don't use Razor Pages must call MapRazorPages. 請參閱本檔中的Razor PagesSee 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

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

[System.object] 是預設的通訊協定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. JsonSwitch to Newtonsoft.Json

如果您使用的是 Newtonsoft 中不支援的功能,您可以切換回 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 專案中使用 NewtonsoftSee Use Newtonsoft.Json in an ASP.NET Core 3.0 SignalR project earlier in this article.

加入執行時間編譯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. 執行時間編譯會補充 views 的組建階段編譯。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. 「組建時間編譯」是預設啟用之 view 編譯的唯一機制。Build-time compilation is the only mechanism for view compilation that's enabled by default. 執行時間依賴 Visual Studio 或dotnet-監看Visual Studio Code,以在偵測到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 中,會在執行的專案(Ctrl + F5)中變更為 .cs. cshtmlrazor檔案,但不會進行調試(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. 安裝 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 Pages,請使用下列程式碼: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 檔案編譯的詳細資訊,請參閱 ASP.NET Core 中 Razor 檔案的先行編譯For more information on Razor file compilation, see ASP.NET Core 中 Razor 檔案的先行編譯.

透過多目標來遷移程式庫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泛型主機的應用程式,請在 ConfigureWebHostIWebHostBuilder 上建立 TestServerFor 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:

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

如需將 .NET Core 首度發行至 Azure App Service 的進度,請參閱 App Service 網站上的官方.Net coreFor progress on the rollout of .NET Core to Azure App Service, see the official .NET Core on App Service website. 在 Azure App Service 上提供 .NET Core 3.0 之前,請遵循將ASP.NET Core preview 版本部署至 Azure App Service中的指示。Until .NET Core 3.0 is available on Azure App Service, follow the instructions at Deploy ASP.NET Core preview release to Azure App Service.