Migrieren von ASP.net Core 2,2 zu 3,0Migrate from ASP.NET Core 2.2 to 3.0
Von Scott Adder und Rick AndersonBy Scott Addie and Rick Anderson
In diesem Artikel wird erläutert, wie ein vorhandenes ASP.net Core 2,2-Projekt auf ASP.net Core 3,0 aktualisiert wird.This article explains how to update an existing ASP.NET Core 2.2 project to ASP.NET Core 3.0. Es ist möglicherweise hilfreich, ein neues ASP.net Core 3,0-Projekt zu erstellen:It might be helpful to create a new ASP.NET Core 3.0 project to:
- Vergleichen Sie mit dem ASP.net Core 2,2-Code.Compare with the ASP.NET Core 2.2 code.
- Kopieren Sie die relevanten Änderungen in das Projekt ASP.net Core 3,0.Copy the relevant changes to your ASP.NET Core 3.0 project.
VoraussetzungenPrerequisites
- Visual StudioVisual Studio
- Visual Studio CodeVisual Studio Code
- Visual Studio für MacVisual Studio for Mac
- Visual Studio 2019 mit der Workload ASP.NET und WebentwicklungVisual Studio 2019 with the ASP.NET and web development workload
- .NET Core 3.0 SDK oder höher.NET Core 3.0 SDK or later
Aktualisieren der .NET Core SDK-Version in „global.json“Update .NET Core SDK version in global.json
Wenn Ihre Lösung auf eine global.js Datei basiert, die auf eine bestimmte .net Core SDK Version ausgerichtet ist, aktualisieren Sie Ihre- version
Eigenschaft auf die Version 3,0, die auf Ihrem Computer installiert ist: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"
}
}
Aktualisieren der ProjektdateiUpdate the project file
Aktualisieren des Ziel FrameworksUpdate the Target Framework
ASP.net Core 3,0 und höher wird nur unter .net Core ausgeführt.ASP.NET Core 3.0 and later only run on .NET Core. Legen Sie für den zielframeworkmoniker (TFM) Folgendes fest netcoreapp3.0
:Set the Target Framework Moniker (TFM) to netcoreapp3.0
:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
</PropertyGroup>
</Project>
Veraltete Paket Verweise entfernenRemove obsolete package references
Eine große Anzahl von nuget-Paketen wird nicht für ASP.net Core 3,0 erstellt.A large number of NuGet packages aren't produced for ASP.NET Core 3.0. Solche Paket Verweise sollten aus der Projektdatei entfernt werden.Such package references should be removed from your project file. Sehen Sie sich die folgende Projektdatei für eine ASP.net Core 2,2-Web-App an: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>
Die aktualisierte Projektdatei für 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>
Die aktualisierte ASP.net Core 3,0-Projektdatei:The updated ASP.NET Core 3.0 project file:
In
<PropertyGroup>
:In the<PropertyGroup>
:- Aktualisiert den TFM auf
netcoreapp3.0
Updates the TFM tonetcoreapp3.0
- Entfernt das-
<AspNetCoreHostingModel>
Element.Removes the<AspNetCoreHostingModel>
element. Weitere Informationen finden Sie unter in-Process-Hostingmodell in diesem Dokument.For more information, see In-process hosting model in this document.
- Aktualisiert den TFM auf
In
<ItemGroup>
:In the<ItemGroup>
:Microsoft.AspNetCore.App
wurde entfernt.Microsoft.AspNetCore.App
is removed. Weitere Informationen finden Sie in diesem Dokument in der frameworkreferenz .For more information, see Framework reference in this document.Microsoft.AspNetCore.Razor.Design
wurde entfernt und in der folgenden Liste von Paketen, die nicht mehr erstellt werden.Microsoft.AspNetCore.Razor.Design
is removed and in the following list of packages no longer being produced.
Um die vollständige Liste der Pakete anzuzeigen, die nicht mehr erstellt werden, wählen Sie die folgende Erweiterungs Liste aus:To see the full list of packages that are no longer produced, select the following expand list:
Klicken Sie, um die Liste der Pakete zu erweitern, die nicht mehr erstellt werdenClick 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. Cookie HymnenMicrosoft.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. Cookie PolicyMicrosoft.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. Razor SeitenMicrosoft.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 . AusgeMicrosoft.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
- Microsoft. aspnetcore.SignalRMicrosoft.AspNetCore.SignalR
- Microsoft. aspnetcore. SignalR . CoreMicrosoft.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
Wichtige Änderungen überprüfenReview breaking changes
Wichtige Änderungen überprüfenReview breaking changes
FrameworkverweisFramework reference
Features von ASP.net Core, die über eines der oben aufgeführten Pakete verfügbar waren, sind als Teil des frei Microsoft.AspNetCore.App
gegebenen Frameworks verfügbar.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. Das freigegebene Framework ist der Satz von Assemblys (DLL-Dateien), die auf dem Computer installiert werden und eine Laufzeitkomponente sowie ein Zielpaket enthalten.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. Weitere Informationen finden Sie unter The shared framework (Das freigegebene Framework).For more information, see The shared framework.
Projekte, die auf das
Microsoft.NET.Sdk.Web
SDK abzielen, verweisen implizit auf dasMicrosoft.AspNetCore.App
-Framework.Projects that target theMicrosoft.NET.Sdk.Web
SDK implicitly reference theMicrosoft.AspNetCore.App
framework.Für diese Projekte sind keine weiteren Verweise erforderlich:No additional references are required for these projects:
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>netcoreapp3.0</TargetFramework> </PropertyGroup> ... </Project>
Projekte, die das Ziel
Microsoft.NET.Sdk
oder dasMicrosoft.NET.Sdk.Razor
SDK sind, sollten eine explizite zu folgenden hinzufügenFrameworkReference
Microsoft.AspNetCore.App
:Projects that targetMicrosoft.NET.Sdk
orMicrosoft.NET.Sdk.Razor
SDK, should add an explicitFrameworkReference
toMicrosoft.AspNetCore.App
:<Project Sdk="Microsoft.NET.Sdk.Razor"> <PropertyGroup> <TargetFramework>netcoreapp3.0</TargetFramework> </PropertyGroup> <ItemGroup> <FrameworkReference Include="Microsoft.AspNetCore.App" /> </ItemGroup> ... </Project>
Framework-abhängige Builds mithilfe von DockerFramework-dependent builds using Docker
Framework-abhängige Builds von Konsolen-apps, die ein Paket verwenden, das vom ASP.net Core Shared Framework abhängt, können den folgenden Laufzeitfehler verursachen: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
ist das freigegebene Framework, das die ASP.net Core Runtime enthält und nur auf dem docker-Image dotnet/Core/ASPNET vorhanden ist.Microsoft.AspNetCore.App
is the shared framework containing the ASP.NET Core runtime and is only present on the dotnet/core/aspnet Docker image. Das 3,0 SDK reduziert die Größe von Framework-abhängigen Builds mit ASP.net Core, indem doppelte Kopien von Bibliotheken, die im freigegebenen Framework verfügbar sind, nicht eingeschlossen werden.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. Dies ist eine potenzielle Einsparung von bis zu 18 MB, aber es ist erforderlich, dass die ASP.net Core-Laufzeit zum Ausführen der app vorhanden bzw. installiert ist.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.
Um zu ermitteln, ob die APP eine Abhängigkeit (entweder direkt oder indirekt) auf dem ASP.net Core freigegebenen Framework hat, überprüfen Sie die runtimeconfig.jsauf die Datei, die während eines Builds/veröffentlichtes Ihrer APP generiert wurde.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. Die folgende JSON-Datei zeigt eine Abhängigkeit vom ASP.net Core Shared Framework: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
}
}
}
Wenn Ihre APP docker verwendet, verwenden Sie ein Basis Image, das ASP.net Core 3,0 enthält.If your app is using Docker, use a base image that includes ASP.NET Core 3.0. Beispiel: docker pull mcr.microsoft.com/dotnet/core/aspnet:3.0
.For example, docker pull mcr.microsoft.com/dotnet/core/aspnet:3.0
.
Paket Verweise für entfernte Assemblys hinzufügenAdd package references for removed assemblies
ASP.net Core 3,0 entfernt einige Assemblys, die zuvor Teil des Microsoft.AspNetCore.App
Paket Verweises waren.ASP.NET Core 3.0 removes some assemblies that were previously part of the Microsoft.AspNetCore.App
package reference. Um zu visualisieren, welche Assemblys entfernt wurden, vergleichen Sie die beiden freigegebenen frameworkordnerTo visualize which assemblies were removed, compare the two shared framework folders. Beispielsweise ein Vergleich der Versionen 2.2.7 und 3.0.0:For example, a comparison of versions 2.2.7 and 3.0.0:
Um die von den entfernten Assemblys bereitgestellten Funktionen weiterhin zu verwenden, verweisen Sie auf die 3,0-Versionen der entsprechenden Pakete:To continue using features provided by the removed assemblies, reference the 3.0 versions of the corresponding packages:
Bei einer Vorlagen generierten Web-App mit einzelnen Benutzerkonten müssen die folgenden Pakete hinzugefügt werden:A template-generated web app with Individual User Accounts requires adding the following packages:
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>netcoreapp3.0</TargetFramework> <UserSecretsId>My-secret</UserSecretsId> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="3.0.0" /> <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.0.0" /> <PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="3.0.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.0.0" /> </ItemGroup> </Project>
Microsoft.EntityFrameworkCoreMicrosoft.EntityFrameworkCore
Weitere Informationen zum Verweisen auf das Datenbankanbieter spezifische Paket finden Sie unter Datenbankanbieter.For more information on referencing the database provider-specific package, see Database Providers.
Benutzeroberfläche von IdentityIdentity UI
Unterstützung für die Identity Benutzeroberfläche kann durch Verweisen auf Microsoft. aspnetcore. hinzugefügt Identity werden. UI -Paket.Support for Identity UI can be added by referencing the Microsoft.AspNetCore.Identity.UI package.
Spa-DiensteSPA Services
Authentifizierung: die Unterstützung für Authentifizierungs Abläufe von Drittanbietern ist als nuget-Pakete verfügbar:Authentication: Support for third-party authentication flows are available as NuGet packages:
- Facebook OAuth (Microsoft. aspnetcore. Authentication. Facebook)Facebook OAuth (Microsoft.AspNetCore.Authentication.Facebook)
- Google OAuth (Microsoft. aspnetcore. Authentication. Google)Google OAuth (Microsoft.AspNetCore.Authentication.Google)
- Microsoft-Konto Authentifizierung (Microsoft. aspnetcore. Authentication. microsoftaccount)Microsoft Account authentication (Microsoft.AspNetCore.Authentication.MicrosoftAccount)
- OpenID Connect-Authentifizierung (Microsoft. aspnetcore. Authentication. openidconnect)OpenID Connect authentication (Microsoft.AspNetCore.Authentication.OpenIdConnect)
- OpenID Connect-bearertoken (Microsoft. aspnetcore. Authentication. jwtbearertoken)OpenID Connect bearer token (Microsoft.AspNetCore.Authentication.JwtBearer)
- Twitter OAuth (Microsoft. aspnetcore. Authentication. Twitter)Twitter OAuth (Microsoft.AspNetCore.Authentication.Twitter)
- Wsfederation-Authentifizierung (Microsoft. aspnetcore. Authentication. wsfederation)WsFederation authentication (Microsoft.AspNetCore.Authentication.WsFederation)
Unterstützung von Formatierung und Inhaltsaushandlung für
System.Net.HttpClient
: das nuget-Paket Microsoft. Aspnet. WebAPI. Client bietet nützliche Erweiterbarkeit fürSystem.Net.HttpClient
mit APIs wieReadAsAsync
undPostJsonAsync
.Formatting and content negotiation support forSystem.Net.HttpClient
: The Microsoft.AspNet.WebApi.Client NuGet package provides useful extensibility toSystem.Net.HttpClient
with APIs such asReadAsAsync
andPostJsonAsync
.Razor Lauf Zeit Kompilierung: die Unterstützung für die Lauf Zeit Kompilierung von Razor Sichten und Seiten ist nun Bestandteil von Microsoft. aspnetcore. MVC. Razor Runtimecompilation.Razor runtime compilation: Support for runtime compilation of Razor views and pages is now part of Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation.
MVC-
Newtonsoft.Json
Unterstützung (JSON.net): die Unterstützung für die Verwendung von MVC mitNewtonsoft.Json
ist nun Bestandteil vonMicrosoft.AspNetCore.Mvc.NewtonsoftJson
.MVCNewtonsoft.Json
(Json.NET) support: Support for using MVC withNewtonsoft.Json
is now part ofMicrosoft.AspNetCore.Mvc.NewtonsoftJson
.
Start ÄnderungenStartup changes
Die folgende Abbildung zeigt die gelöschten und geänderten Zeilen in einer ASP.net Core-Web-App mit 2,2- Razor Seiten:The following image shows the deleted and changed lines in an ASP.NET Core 2.2 Razor Pages Web app:
In der vorangehenden Abbildung ist gelöschter Code rot dargestellt.In the preceding image, deleted code is shown in red. Der gelöschte Code zeigt keinen cookie options Code an, der vor dem Vergleichen der Dateien gelöscht wurde.The deleted code doesn't show cookie options code, which was deleted prior to comparing the files.
In der folgenden Abbildung werden die hinzugefügten und geänderten Zeilen in einer ASP.net Core-Web-App mit 3,0- Razor Seiten angezeigtThe following image shows the added and changed lines in an ASP.NET Core 3.0 Razor Pages Web app:
In der vorangehenden Abbildung ist der hinzugefügte Code grün dargestellt.In the preceding image, added code is shown in green. Weitere Informationen zu den folgenden Änderungen:For information on the following changes:
services.AddMvc
Informationen zu finden Sie unterservices.AddRazorPages
MVC-Dienst Registrierung in diesem Dokument.services.AddMvc
toservices.AddRazorPages
, see MVC service registration in this document.CompatibilityVersion
finden Sie unter Kompatibilitätsversion für ASP.NET Core MVC .CompatibilityVersion
, see Kompatibilitätsversion für ASP.NET Core MVC.IHostingEnvironment
zuIWebHostEnvironment
finden Sie diese GitHub-Ankündigung.IHostingEnvironment
toIWebHostEnvironment
, see this GitHub announcement.app.UseAuthorization
wurde den Vorlagen hinzugefügt, um anzuzeigen, dass die Middleware für die Bestell Autorisierung hinzugefügt werden muss.app.UseAuthorization
was added to the templates to show the order authorization middleware must be added. Wenn die APP keine Autorisierung verwendet, können Sie den-Befehl problemlos entfernenapp.UseAuthorization
.If the app doesn't use authorization, you can safely remove the call toapp.UseAuthorization
.app.UseEndpoints
finden Sie in diesem Dokument unter Razor Seiten oder Migrieren Startup.Configure .app.UseEndpoints
, see Razor Pages or Migrate Startup.Configure in this document.
Analyse UnterstützungAnalyzer support
Projekte, die Microsoft.NET.Sdk.Web
implizit auf Analysen abzielen, die zuvor als Teil des Pakets Microsoft. aspnetcore. MVC. Analysen ausgeliefert wurden.Projects that target Microsoft.NET.Sdk.Web
implicitly reference analyzers previously shipped as part of the Microsoft.AspNetCore.Mvc.Analyzers package. Es sind keine zusätzlichen Verweise erforderlich, um diese zu aktivieren.No additional references are required to enable these.
Wenn Ihre APP API-Analysen verwendet, die zuvor mit dem Paket Microsoft. aspnetcore. MVC. API. Analysen ausgeliefert wurden, bearbeiten Sie die Projektdatei so, dass Sie auf die Analysen verweist, die als Teil des .net Core Web SDK ausgeliefert werden: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 KlassenbibliothekRazor Class Library
Razor In Klassen Bibliotheks Projekten, die Benutzeroberflächen Komponenten für MVC bereitstellen, muss die- AddRazorSupportForMvc
Eigenschaft in der Projektdatei festgelegt werden: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-HostingmodellIn-process hosting model
-Projekte werden standardmäßig in ASP.net Core 3,0 oder höher auf das in-Process-Hostingmodell eingestellt.Projects default to the in-process hosting model in ASP.NET Core 3.0 or later. Wenn der Wert lautet, können Sie optional die- <AspNetCoreHostingModel>
Eigenschaft in der Projektdatei entfernen InProcess
.You may optionally remove the <AspNetCoreHostingModel>
property in the project file if its value is InProcess
.
KestrelKestrel
KonfigurationConfiguration
Migrieren Sie die Kestrel-Konfiguration zum von bereitgestellten Webhost -Generator ConfigureWebHostDefaults
(Program.cs):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>();
});
Wenn die APP den Host mit ConfigureWebHost
anstelle von manuell erstellt ConfigureWebHostDefaults
, müssen Sie UseKestrel
auf dem Webhost-Generator aufzurufen:If the app creates the host manually with ConfigureWebHost
instead of ConfigureWebHostDefaults
, call UseKestrel
on the web host builder:
public static void Main(string[] args)
{
var host = new HostBuilder()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureWebHost(webBuilder =>
{
webBuilder.UseKestrel(serverOptions =>
{
// Set properties and call methods on options
})
.UseIISIntegration()
.UseStartup<Startup>();
})
.Build();
host.Run();
}
Verbindungs-Middleware ersetzt Verbindungs AdapterConnection Middleware replaces Connection Adapters
Verbindungs Adapter ( Microsoft.AspNetCore.Server.Kestrel.Core.Adapter.Internal.IConnectionAdapter
) wurden aus Kestrel entfernt.Connection Adapters (Microsoft.AspNetCore.Server.Kestrel.Core.Adapter.Internal.IConnectionAdapter
) have been removed from Kestrel. Ersetzen Sie Verbindungs Adapter durch Verbindungs Middleware.Replace Connection Adapters with Connection Middleware. Die Verbindungs Middleware ähnelt http-Middleware in der ASP.net Core Pipeline, aber für Verbindungen auf niedrigerer Ebene.Connection Middleware is similar to HTTP Middleware in the ASP.NET Core pipeline but for lower-level connections. HTTPS und Verbindungs Protokollierung:HTTPS and connection logging:
- Wurden von Verbindungs Adaptern zur Verbindungs Middleware verschoben.Have been moved from Connection Adapters to Connection Middleware.
- Diese Erweiterungs Methoden funktionieren wie in früheren Versionen von ASP.net Core.These extension methods work as in previous versions of ASP.NET Core.
Weitere Informationen finden Sie im Abschnitt "tlsfilterconnectionhandler" im Abschnitt "listenoptions. Protokolls" im Kestrel-Artikel.For more information, see the TlsFilterConnectionHandler example in the ListenOptions.Protocols section of the Kestrel article.
Transport Abstraktionen verschoben und öffentlich gemachtTransport abstractions moved and made public
Die Kestrel-Transportschicht wurde in Connections.Abstractions
als öffentliche Schnittstelle verfügbar gemacht.The Kestrel transport layer has been exposed as a public interface in Connections.Abstractions
. Als Teil dieser Updates:As part of these updates:
Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions
und zugeordnete Typen wurden entfernt.Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions
and associated types have been removed.- NoDelay wurde von ListenOptions zu den Transport Optionen verschoben.NoDelay was moved from ListenOptions to the transport options.
Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal.SchedulingMode
wurde aus entfernt KestrelServerOptions .Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal.SchedulingMode
was removed from KestrelServerOptions.
Weitere Informationen finden Sie in den folgenden GitHub-Ressourcen:For more information, see the following GitHub resources:
- Client/Server-Netzwerk Abstraktionen (dotnet/aspnetcore-#10308)Client/server networking abstractions (dotnet/AspNetCore #10308)
- Implementieren Sie die neue Fundament-Listener-Abstraktion und REPLAT Kestrel (dotnet/aspnetcore-#10321).Implement new bedrock listener abstraction and re-plat Kestrel on top (dotnet/AspNetCore #10321)
Kestrel-Anforderungs Nachspann HeaderKestrel Request trailer headers
Für apps, die auf frühere Versionen von ASP.net Core abzielen:For apps that target earlier versions of ASP.NET Core:
- Kestrel fügt der Auflistung der Anforderungs Header HTTP/1.1-Auflistungs Header hinzu.Kestrel adds HTTP/1.1 chunked trailer headers into the request headers collection.
- Nach dem Lesen des Anforderungs Texts sind die nach dem Ende des Anforderungs Texts verfügbar.Trailers are available after the request body is read to the end.
Dies bewirkt einige Bedenken bezüglich der Mehrdeutigkeit zwischen Headern und nach Spann, sodass die Nachspann in eine neue Sammlung ( RequestTrailerExtensions
) in 3,0 verschoben wurden.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-Anforderungs Nachspann:HTTP/2 request trailers are:
- Nicht verfügbar in ASP.net Core 2,2.Not available in ASP.NET Core 2.2.
- Verfügbar in 3,0 als
RequestTrailerExtensions
.Available in 3.0 asRequestTrailerExtensions
.
Für den Zugriff auf diese Nachspann sind neue Anforderungs Erweiterungs Methoden vorhanden.New request extension methods are present to access these trailers. Wie bei HTTP/1.1 sind Nachspann verfügbar, nachdem der Anforderungs Text bis zum Ende gelesen wurde.As with HTTP/1.1, trailers are available after the request body is read to the end.
Für die Version 3,0 sind die folgenden RequestTrailerExtensions
Methoden verfügbar:For the 3.0 release, the following RequestTrailerExtensions
methods are available:
GetDeclaredTrailers
: Ruft den AnforderungsTrailer
Header ab, der auflistet, welche Nachspann nach dem Text erwartet werden.GetDeclaredTrailers
: Gets the requestTrailer
header that lists which trailers to expect after the body.SupportsTrailers
: Gibt an, ob die Anforderung das Empfangen von nach Spann Headern unterSupportsTrailers
: Indicates if the request supports receiving trailer headers.CheckTrailersAvailable
: Überprüft, ob die Anforderung Nachspann unterstützt und ob Sie gelesen werden können.CheckTrailersAvailable
: Checks if the request supports trailers and if they're available to be read. Bei dieser Überprüfung wird nicht davon ausgegangen, dass zum Lesen von nach spannendenThis check doesn't assume that there are trailers to read. Möglicherweise gibt es keine zu lesenden Nachspann, auch wenntrue
von dieser Methode zurückgegeben wird.There might be no trailers to read even iftrue
is returned by this method.GetTrailer
: Ruft den angeforderten nachfolgenden Header aus der Antwort ab.GetTrailer
: Gets the requested trailing header from the response. Überprüfen SieSupportsTrailers
vor dem Aufrufen vonGetTrailer
, oder NotSupportedException kann eintreten, wenn die Anforderung keine nachfolgenden Header unterstützt.CheckSupportsTrailers
before callingGetTrailer
, or a NotSupportedException may occur if the request doesn't support trailing headers.
Weitere Informationen finden Sie unter Put Request Trailers in a separate Collection (dotnet/aspnetcore-#10410).For more information, see Put request trailers in a separate collection (dotnet/AspNetCore #10410).
Allowsynchronousio deaktiviertAllowSynchronousIO disabled
AllowSynchronousIO
aktiviert oder deaktiviert synchrone e/a-APIs, wie HttpRequest.Body.Read
z HttpResponse.Body.Write
. b Stream.Flush
., und.AllowSynchronousIO
enables or disables synchronous I/O APIs, such as HttpRequest.Body.Read
, HttpResponse.Body.Write
, and Stream.Flush
. Diese APIs sind eine Quelle der Thread Hungersnot, die zu app-Abstürzen führt.These APIs are a source of thread starvation leading to app crashes. In 3.0 ist AllowSynchronousIO
standardmäßig deaktiviert.In 3.0, AllowSynchronousIO
is disabled by default. Weitere Informationen finden Sie im Abschnitt "Synchrone e/a" im Kestrel-Artikel.For more information, see the Synchronous I/O section in the Kestrel article.
Wenn eine synchrone e/a erforderlich ist, kann Sie aktiviert werden, indem die- AllowSynchronousIO
Option auf dem verwendeten Server konfiguriert wird ( ConfigureKestrel
z. b. bei Verwendung von 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). Beachten Sie, dass Server (Kestrel, httpsys, Testserver usw.) über eine eigene AllowSynchronousIO
Option verfügen, die sich nicht auf andere Server auswirkt.Note that servers (Kestrel, HttpSys, TestServer, etc.) all have their own AllowSynchronousIO
option that won't affect other servers. Synchrone e/a-Vorgänge können für alle Server auf Anforderungs Basis aktiviert werden. verwenden Sie dazu die folgende IHttpBodyControlFeature.AllowSynchronousIO
Option:Synchronous 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;
}
Wenn Sie Probleme mit TextWriter Implementierungen oder anderen Streams haben,die synchrone APIs in verwerfen aufzurufen, müssen Sie stattdessen die neue DisposeAsync API abrufen.If you have trouble with TextWriter implementations or other streams that call synchronous APIs in Dispose, call the new DisposeAsync API instead.
Weitere Informationen finden Sie unter [Ankündigung] allowsynchronousio deaktiviert auf allen Servern (dotnet/aspnetcore-#7644).For more information, see [Announcement] AllowSynchronousIO disabled in all servers (dotnet/AspNetCore #7644).
Ausgabe formatiererpufferungOutput formatter buffering
Newtonsoft.Jsauf XmlSerializer -,-und- DataContractSerializer basierten Ausgabe Formatierern unterstützen nur die synchrone Serialisierung.Newtonsoft.Json, XmlSerializer, and DataContractSerializer based output formatters only support synchronous serialization. Damit diese Formatierer mit den allowsynchronousio -Einschränkungen des Servers arbeiten können, puffert MVC die Ausgabe dieser Formatierer, bevor Sie auf den Datenträger geschrieben wird.To allow these formatters to work with the AllowSynchronousIO restrictions of the server, MVC buffers the output of these formatters before writing to disk. Aufgrund der Pufferung schließt MVC den Content-Length-Header ein, wenn er mithilfe dieser Formatierer antwortet.As a result of buffering, MVC will include the Content-Length header when responding using these formatters.
System.Text.Json unterstützt die asynchrone Serialisierung System.Text.Json
. Folglich wird der basierte Formatierer nicht gepuffert.System.Text.Json supports asynchronous serialization and consequently the System.Text.Json
based formatter does not buffer. Verwenden Sie diesen Formatierer, um die Leistung zu verbessern.Consider using this formatter for improved performance.
Zum Deaktivieren der Pufferung können Anwendungen SuppressOutputFormatterBuffering beim Starten konfigurieren:To disable buffering, applications can configure SuppressOutputFormatterBuffering in their startup:
services.AddControllers(options => options.SuppressOutputFormatterBuffering = true)
Beachten Sie, dass dies dazu führen kann, dass die Anwendung eine Lauf Zeit Ausnahme auslöst, wenn AllowSynchronousIO
nicht auch konfiguriert ist.Note that this may result in the application throwing a runtime exception if AllowSynchronousIO
isn't also configured.
Die Assembly "Microsoft. aspnetcore. Server. Kestrel. https" wurde entfernt.Microsoft.AspNetCore.Server.Kestrel.Https assembly removed
In ASP.net Core 2,1 wurde der Inhalt Microsoft.AspNetCore.Server.Kestrel.Https.dll in Microsoft.AspNetCore.Server.Kestrel.Core.dll verschoben.In ASP.NET Core 2.1, the contents of Microsoft.AspNetCore.Server.Kestrel.Https.dll were moved to Microsoft.AspNetCore.Server.Kestrel.Core.dll. Dabei handelt es sich um ein nicht Erbrechtes Update mit TypeForwardedTo
Attributen.This was a non-breaking update using TypeForwardedTo
attributes. Bei 3,0 wurden die leeren Microsoft.AspNetCore.Server.Kestrel.Https.dll Assembly und das nuget-Paket entfernt.For 3.0, the empty Microsoft.AspNetCore.Server.Kestrel.Https.dll assembly and the NuGet package have been removed.
Bibliotheken, die auf Microsoft. aspnetcore. Server. Kestrel. HTTPS verweisen, sollten ASP.net Core Abhängigkeiten auf 2,1 oder höher aktualisieren.Libraries referencing Microsoft.AspNetCore.Server.Kestrel.Https should update ASP.NET Core dependencies to 2.1 or later.
Apps und Bibliotheken, die auf ASP.net Core 2,1 oder höher abzielen, sollten alle direkten Verweise auf das Paket Microsoft. aspnetcore. Server. Kestrel. HTTPS entfernen.Apps and libraries targeting ASP.NET Core 2.1 or later should remove any direct references to the Microsoft.AspNetCore.Server.Kestrel.Https package.
Unterstützung für Newtonsoft.Json (JSON.net)Newtonsoft.Json (Json.NET) support
Im Rahmen der Arbeit zur Verbesserung der ASP.net Core freigegebenen Frameworkswurde Newtonsoft.Json (JSON.net) aus dem ASP.net Core Shared Framework entfernt.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.
Der Standard-JSON-Serialisierer für ASP.net Core ist jetzt System.Text.Json , der in .net Core 3,0 neu ist.The default JSON serializer for ASP.NET Core is now System.Text.Json, which is new in .NET Core 3.0. Verwenden Sie nach Möglichkeit die Verwendung von System.Text.Json
.Consider using System.Text.Json
when possible. Dies ist eine hohe Leistung und erfordert keine zusätzliche Bibliotheks Abhängigkeit.It's high-performance and doesn't require an additional library dependency. Da jedoch System.Text.Json
neu ist, fehlen möglicherweise derzeit die Features, die Ihre APP benötigt.However, since System.Text.Json
is new, it might currently be missing features that your app needs. Weitere Informationen finden Sie unter Migrieren von Newtonsoft.Json zu System.Text.Json.For more information, see How to migrate from Newtonsoft.Json to System.Text.Json.
Verwenden von Newtonsoft.Json in einem ASP.net Core 3,0- SignalR ProjektUse Newtonsoft.Json in an ASP.NET Core 3.0 SignalR project
Installieren Sie Microsoft. aspnetcore. SignalR Das nuget-Paket "Protokolls. newtonsoft JSON ".Install the Microsoft.AspNetCore.SignalR.Protocols.NewtonsoftJson NuGet package.
Verketten Sie auf dem Client einen
AddNewtonsoftJsonProtocol
Methoden Aufrufder-HubConnectionBuilder
Instanz:On the client, chain anAddNewtonsoftJsonProtocol
method call to theHubConnectionBuilder
instance:new HubConnectionBuilder() .WithUrl("/chathub") .AddNewtonsoftJsonProtocol(...) .Build();
Verketten Sie auf dem-Server einen
AddNewtonsoftJsonProtocol
Methodenaufrufe des-AddSignalR
Methoden Aufrufes inStartup.ConfigureServices
:On the server, chain anAddNewtonsoftJsonProtocol
method call to theAddSignalR
method call inStartup.ConfigureServices
:services.AddSignalR() .AddNewtonsoftJsonProtocol(...);
Verwenden von Newtonsoft.Json in einem ASP.net Core 3,0-MVC-ProjektUse Newtonsoft.Json in an ASP.NET Core 3.0 MVC project
Installieren Sie das
Microsoft.AspNetCore.Mvc.NewtonsoftJson
Paket.Install theMicrosoft.AspNetCore.Mvc.NewtonsoftJson
package.Aktualisieren
Startup.ConfigureServices
, um aufzurufenAddNewtonsoftJson
.UpdateStartup.ConfigureServices
to callAddNewtonsoftJson
.services.AddMvc() .AddNewtonsoftJson();
AddNewtonsoftJson
ist mit den neuen Registrierungsmethoden für den MVC-Dienst kompatibel:AddNewtonsoftJson
is compatible with the new MVC service registration methods:AddRazorPages
AddControllersWithViews
AddControllers
services.AddControllers() .AddNewtonsoftJson();
Newtonsoft.Json
Einstellungen können im-Befehl festgelegt werdenAddNewtonsoftJson
:Newtonsoft.Json
settings can be set in the call toAddNewtonsoftJson
:services.AddMvc() .AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver());
Hinweis: Wenn die
AddNewtonsoftJson
Methode nicht verfügbar ist, stellen Sie sicher, dass Sie das Paket installiert habenMicrosoft.AspNetCore.Mvc.NewtonsoftJson
.Note: If theAddNewtonsoftJson
method isn't available, make sure that you installed theMicrosoft.AspNetCore.Mvc.NewtonsoftJson
package. Ein häufiger Fehler besteht darin, die Newtonsoft.Jsfür das Paket anstelle desMicrosoft.AspNetCore.Mvc.NewtonsoftJson
Pakets zu installieren.A common error is to install the Newtonsoft.Json package instead of theMicrosoft.AspNetCore.Mvc.NewtonsoftJson
package.
Weitere Informationen finden Sie unter Hinzufügen Newtonsoft.Json-based JSON-Formatunterstützung.For more information, see Add Newtonsoft.Json-based JSON format support.
MVC-Dienst RegistrierungMVC service registration
In ASP.net Core 3,0 werden neue Optionen zum Registrieren von MVC-Szenarien in hinzugefügt Startup.ConfigureServices
.ASP.NET Core 3.0 adds new options for registering MVC scenarios inside Startup.ConfigureServices
.
Drei neue Erweiterungs Methoden der obersten Ebene, die sich auf MVC-Szenarios für beziehen, IServiceCollection
sind verfügbar.Three new top-level extension methods related to MVC scenarios on IServiceCollection
are available. Vorlagen verwenden diese neuen Methoden anstelle von AddMvc
.Templates use these new methods instead of AddMvc
. Verhält sich jedoch AddMvc
weiterhin wie in früheren Versionen.However, AddMvc
continues to behave as it has in previous releases.
Im folgenden Beispiel wird die Unterstützung für Controller und API-Funktionen hinzugefügt, jedoch keine Sichten oder Seiten.The following example adds support for controllers and API-related features, but not views or pages. Die API-Vorlage verwendet diesen Code:The API template uses this code:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
Im folgenden Beispiel werden die Unterstützung für Controller, API-bezogene Features und Sichten, aber keine Seiten hinzugefügt.The following example adds support for controllers, API-related features, and views, but not pages. Die Vorlage Webanwendung (MVC) verwendet folgenden Code:The Web Application (MVC) template uses this code:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}
Im folgenden Beispiel wird die Unterstützung für Razor Seiten und die minimale Controller Unterstützung hinzugefügt.The following example adds support for Razor Pages and minimal controller support. Die Webanwendungsvorlage verwendet diesen Code:The Web Application template uses this code:
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
}
Die neuen Methoden können ebenfalls kombiniert werden.The new methods can also be combined. Das folgende Beispiel entspricht dem Aufrufen von AddMvc
in 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 StartcodeRouting startup code
Wenn eine APP UseMvc
oder aufruft UseSignalR
, migrieren Sie die APP nach Möglichkeit zum Endpunkt Routing .If an app calls UseMvc
or UseSignalR
, migrate the app to Endpoint Routing if possible. Um die Kompatibilität mit dem Endpunkt Routing mit früheren Versionen von MVC zu verbessern, haben wir einige der Änderungen in der URL-Generierung wieder hergestellt, die in ASP.net Core 2,2 eingeführt wurden.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. Wenn bei der Verwendung des Endpunkt Routings in 2,2 Probleme auftreten, erwarten Sie Verbesserungen in ASP.net Core 3,0 mit folgenden Ausnahmen:If you experienced problems using Endpoint Routing in 2.2, expect improvements in ASP.NET Core 3.0 with the following exceptions:
- Wenn die APP implementiert
IRouter
oder von der Anwendung erbtRoute
, verwenden Sie dynamicroutevaluestransex als Ersatz.If the app implementsIRouter
or inherits fromRoute
, use DynamicRouteValuesTransformer as the replacement. - Wenn die APP direkt
RouteData.Routers
in MVC zugreift, um URLs zu analysieren, können Sie dies durch die Verwendung von linkparser. parspathbyendpointnameersetzen.If the app directly accessesRouteData.Routers
inside MVC to parse URLs, you can replace this with use of LinkParser.ParsePathByEndpointName.- Hiermit wird die Route mit einem Routennamen definiert.Define the route with a route name.
- Verwenden Sie,
LinkParser.ParsePathByEndpointName
und übergeben Sie den gewünschten Routennamen.UseLinkParser.ParsePathByEndpointName
and pass in the desired route name.
Das Endpunkt Routing unterstützt die gleiche Routing Muster Syntax und die Funktionen zum Erstellen von Routen Mustern wie IRouter
.Endpoint Routing supports the same route pattern syntax and route pattern authoring features as IRouter
. Das Endpunkt Routing unterstützt IRouteConstraint
.Endpoint Routing supports IRouteConstraint
. Das Endpunkt Routing unterstützt [Route]
, [HttpGet]
und die anderen MVC-Routing Attribute.Endpoint routing supports [Route]
, [HttpGet]
, and the other MVC routing attributes.
Bei den meisten Anwendungen Startup
müssen nur Änderungen vorgenommen werden.For most applications, only Startup
requires changes.
Migrieren Startup.ConfigureMigrate Startup.Configure
Allgemeine Hinweise:General advice:
Fügen Sie
UseRouting
hinzu.AddUseRouting
.Wenn die APP aufruft
UseStaticFiles
, platzieren Sie esUseStaticFiles
vorUseRouting
.If the app callsUseStaticFiles
, placeUseStaticFiles
beforeUseRouting
.Wenn die APP Authentifizierungs-/Autorisierungsfeatures wie
AuthorizePage
oder verwendet[Authorize]
, platzieren Sie den-Befehl unterUseAuthentication
undUseAuthorization
: nach undUseRouting
UseCors
, aber vorUseEndpoints
:If the app uses authentication/authorization features such asAuthorizePage
or[Authorize]
, place the call toUseAuthentication
andUseAuthorization
: after,UseRouting
andUseCors
, but beforeUseEndpoints
:public void Configure(IApplicationBuilder app) { ... app.UseStaticFiles(); app.UseRouting(); app.UseCors(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
Ersetzen Sie
UseMvc
oderUseSignalR
durchUseEndpoints
.ReplaceUseMvc
orUseSignalR
withUseEndpoints
.Wenn die APP cors -Szenarien (z. b.) verwendet,
[EnableCors]
platzieren Sie den-AnrufeUseCors
vor allen anderen Middleware, die cors verwenden (zUseCors
. b. platzieren vorUseAuthentication
,UseAuthorization
undUseEndpoints
).If the app uses CORS scenarios, such as[EnableCors]
, place the call toUseCors
before any other middleware that use CORS (for example, placeUseCors
beforeUseAuthentication
,UseAuthorization
, andUseEndpoints
).Ersetzen
IHostingEnvironment
Sie durch,IWebHostEnvironment
und fügen Sie eine-using
Anweisung für den Microsoft.Extensions.Hosting Namespace hinzu.ReplaceIHostingEnvironment
withIWebHostEnvironment
and add ausing
statement for the Microsoft.Extensions.Hosting namespace.Ersetzen Sie dies
IApplicationLifetime
durch IHostApplicationLifetime (- Microsoft.Extensions.Hosting Namespace).ReplaceIApplicationLifetime
with IHostApplicationLifetime (Microsoft.Extensions.Hosting namespace).Ersetzen Sie dies
EnvironmentName
durch Environments (- Microsoft.Extensions.Hosting Namespace).ReplaceEnvironmentName
with Environments (Microsoft.Extensions.Hosting namespace).
Der folgende Code ist ein Beispiel für Startup.Configure
eine typische ASP.net Core 2,2-App: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?}");
});
}
Nach dem Aktualisieren des vorherigen Startup.Configure
Codes: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?}");
});
}
Warnung
Bei den meisten apps müssen Aufrufe von UseAuthentication
, UseAuthorization
und UseCors
zwischen den Aufrufen von und auftreten UseRouting
, UseEndpoints
um wirksam zu werden.For most apps, calls to UseAuthentication
, UseAuthorization
, and UseCors
must appear between the calls to UseRouting
and UseEndpoints
to be effective.
IntegritätsprüfungenHealth Checks
Integritätsprüfungen verwenden das Endpunktrouting mit dem generischen Host.Health Checks use endpoint routing with the Generic Host. Rufen Sie in Startup.Configure
auf der Endpunkterstellung mit der Endpunkt-URL oder dem relativen Pfad MapHealthChecks
auf:In Startup.Configure
, call MapHealthChecks
on the endpoint builder with the endpoint URL or relative path:
app.UseEndpoints(endpoints =>
{
endpoints.MapHealthChecks("/health");
});
Für Endpunkte für Integritätsprüfungen gilt Folgendes:Health Checks endpoints can:
- Sie geben mindestens einen zugelassenen Host oder Port an.Specify one or more permitted hosts/ports.
- Sie erfordern Autorisierung.Require authorization.
- Sie erfordern CORS.Require CORS.
Weitere Informationen finden Sie unter Integritätsprüfungen in ASP.NET Core.For more information, see Integritätsprüfungen in ASP.NET Core.
Leitfaden zur Sicherheit von MiddlewareSecurity middleware guidance
Unterstützung für die Autorisierung und cors ist in Bezug auf den Middleware -Ansatz einheitlich.Support for authorization and CORS is unified around the middleware approach. Dies ermöglicht die Verwendung derselben Middleware und derselben Funktionalität in diesen Szenarien.This allows use of the same middleware and functionality across these scenarios. In dieser Version wird eine aktualisierte Autorisierungs Middleware bereitgestellt, und die cors-Middleware wird verbessert, sodass Sie die von MVC-Controllern verwendeten Attribute verstehen kann.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
Zuvor war es möglicherweise schwierig, cors zu konfigurieren.Previously, CORS could be difficult to configure. Die Middleware wurde zur Verwendung in einigen Anwendungsfällen bereitgestellt, aber MVC-Filter waren in anderen Anwendungsfällen ohne die Middleware vorgesehen.Middleware was provided for use in some use cases, but MVC filters were intended to be used without the middleware in other use cases. Bei ASP.net Core 3,0 wird empfohlen, dass alle apps, die cors benötigen, die cors-Middleware zusammen mit dem Endpunkt Routing verwenden.With ASP.NET Core 3.0, we recommend that all apps that require CORS use the CORS Middleware in tandem with Endpoint Routing. UseCors
kann mit einer Standard Richtlinie angegeben werden, und [EnableCors]
die-und- [DisableCors]
Attribute können verwendet werden, um die Standard Richtlinie nach Bedarf zu überschreiben.UseCors
can be provided with a default policy, and [EnableCors]
and [DisableCors]
attributes can be used to override the default policy where required.
Im folgenden Beispiel:In the following example:
- Cors ist für alle Endpunkte mit der
default
benannten Richtlinie aktiviert.CORS is enabled for all endpoints with thedefault
named policy. - Die-
MyController
Klasse deaktiviert cors mit dem-[DisableCors]
Attribut.TheMyController
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
{
...
}
AutorisierungAuthorization
In früheren Versionen von ASP.net Core wurde Unterstützung der Autorisierung über das-Attribut bereitgestellt [Authorize]
.In earlier versions of ASP.NET Core, authorization support was provided via the [Authorize]
attribute. Die Autorisierungs Middleware war nicht verfügbar.Authorization middleware wasn't available. In ASP.net Core 3,0 ist die Autorisierungs Middleware erforderlich.In ASP.NET Core 3.0, authorization middleware is required. Es wird empfohlen, die ASP.net Core Autorisierungs Middleware ( UseAuthorization
) direkt nach zu platzieren UseAuthentication
.We recommend placing the ASP.NET Core Authorization Middleware (UseAuthorization
) immediately after UseAuthentication
. Die Middleware für die Autorisierung kann auch mit einer Standard Richtlinie konfiguriert werden, die überschrieben werden kann.The Authorization Middleware can also be configured with a default policy, which can be overridden.
In ASP.net Core 3,0 oder höher UseAuthorization
wird in aufgerufen Startup.Configure
, und für Folgendes ist ein angemeldeter HomeController
Benutzer erforderlich: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()
{
...
}
}
Wenn Sie das Endpunkt Routing verwenden, wird empfohlen, <xref:Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter>
die Autorisierungs Middleware zu konfigurieren und stattdessen darauf zu vertrauen.When using endpoint routing, we recommend against configuring <xref:Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter>
and instead relying on the Authorization middleware. Wenn die APP AuthorizeFilter
als globaler Filter in MVC verwendet, empfiehlt es sich, den Code so zu umgestalten, dass er eine Richtlinie im-Befehl bereitstellt 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
.
Das DefaultPolicy
ist anfänglich so konfiguriert, dass eine Authentifizierung erforderlich ist, sodass keine zusätzliche Konfiguration erforderlich ist.The DefaultPolicy
is initially configured to require authentication, so no additional configuration is required. Im folgenden Beispiel werden die MVC-Endpunkte als markiert, RequireAuthorization
sodass alle Anforderungen auf der Grundlage von autorisiert werden müssen DefaultPolicy
.In the following example, MVC endpoints are marked as RequireAuthorization
so that all requests must be authorized based on the DefaultPolicy
. Der ermöglicht jedoch den HomeController
Zugriff, ohne dass der Benutzer sich bei der App anmeldet. Dies liegt an folgendem [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
{
...
}
Autorisierung für bestimmte EndpunkteAuthorization for specific endpoints
Die Autorisierung kann auch für bestimmte Klassen von Endpunkten konfiguriert werden.Authorization can also be configured for specific classes of endpoints. Der folgende Code ist ein Beispiel für die Umstellung einer MVC-APP, die eine globale AuthorizeFilter
in eine APP mit einer bestimmten Richtlinie konfiguriert, die eine Autorisierung erfordert: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();
});
}
}
Richtlinien können auch angepasst werden.Policies can also be customized. Der DefaultPolicy
ist so konfiguriert, dass eine Authentifizierung erforderlich ist: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
{
Alternativ können alle Endpunkte so konfiguriert werden, dass Sie ohne [Authorize]
oder RequireAuthorization
durch Konfigurieren von eine Autorisierung erfordern FallbackPolicy
.Alternatively, all endpoints can be configured to require authorization without [Authorize]
or RequireAuthorization
by configuring a FallbackPolicy
. Der FallbackPolicy
unterscheidet sich vom DefaultPolicy
.The FallbackPolicy
is different from the DefaultPolicy
. DefaultPolicy
Wird von oder ausgelöst [Authorize]
RequireAuthorization
, während das FallbackPolicy
ausgelöst wird, wenn keine andere Richtlinie festgelegt ist.The DefaultPolicy
is triggered by [Authorize]
or RequireAuthorization
, while the FallbackPolicy
is triggered when no other policy is set. FallbackPolicy
ist anfänglich so konfiguriert, dass Anforderungen ohne Autorisierung zugelassen werden.FallbackPolicy
is initially configured to allow requests without authorization.
Das folgende Beispiel ist identisch mit dem vorherigen DefaultPolicy
Beispiel, verwendet jedoch FallbackPolicy
, um immer eine Authentifizierung für alle Endpunkte anzufordern, außer wenn [AllowAnonymous]
angegeben ist: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
{
...
}
Die Autorisierung durch Middleware funktioniert, ohne dass das Framework über bestimmte Kenntnisse der Autorisierung verfügt.Authorization by middleware works without the framework having any specific knowledge of authorization. Integritäts Prüfungen haben beispielsweise keine spezifischen Kenntnisse der Autorisierung, aber Integritätsprüfungen können eine konfigurierbare Autorisierungs Richtlinie aufweisen, die von der Middleware angewendet wird.For instance, health checks has no specific knowledge of authorization, but health checks can have a configurable authorization policy applied by the middleware.
Außerdem kann jeder Endpunkt seine Autorisierungs Anforderungen anpassen.Additionally, each endpoint can customize its authorization requirements. Im folgenden Beispiel wird die UseAuthorization
Autorisierung mit der verarbeitet DefaultPolicy
, aber der Integritäts /healthz
Prüfung-Endpunkt erfordert einen admin
Benutzer: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", });
});
}
Der Schutz wird für einige Szenarien implementiert.Protection is implemented for some scenarios. Die Middleware für Endpunkte löst eine Ausnahme aus, wenn eine Autorisierungs-oder cors-Richtlinie aufgrund fehlender Middleware übersprungen wird.Endpoints Middleware throws an exception if an authorization or CORS policy is skipped due to missing middleware. Analyse Unterstützung, um zusätzliches Feedback zur Fehlkonfiguration bereitzustellen.Analyzer support to provide additional feedback about misconfiguration is in progress.
Benutzerdefinierte Autorisierungs HandlerCustom authorization handlers
Wenn die APP benutzerdefinierte Autorisierungs Handlerverwendet, übergibt das Endpunkt Routing einen anderen Ressourcentyp an Handler als MVC.If the app uses custom authorization handlers, endpoint routing passes a different resource type to handlers than MVC. Handler, die erwarten, dass die Kontext Ressource des Autorisierungs Handler vom Typ ist AuthorizationFilterContext (der von MVC-Filtern bereitgestellteRessourcentyp), muss aktualisiert werden, damit die Ressourcen des Typs RouteEndpoint (der Ressourcentyp, der den Autorisierungs Handlern durch Endpunkt Routing zugewiesen ist) verarbeitet werdenHandlers 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).
Da MVC weiterhin AuthorizationFilterContext
Ressourcen verwendet, ist es möglicherweise erforderlich, beide Arten von Ressourcen zu verarbeiten, wenn die APP MVC-Autorisierungs Filter zusammen mit der Endpunkt Weiterleitungs Autorisierung verwendet.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
Die Zuordnung von SignalR Hubs erfolgt nun in UseEndpoints
.Mapping of SignalR hubs now takes place inside UseEndpoints
.
Ordnen Sie jeden Hub mit zu MapHub
.Map each hub with MapHub
. Wie in früheren Versionen wird jeder Hub explizit aufgelistet.As in previous versions, each hub is explicitly listed.
Im folgenden Beispiel wird die Unterstützung für den ChatHub
SignalR Hub hinzugefügt: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>();
});
}
Es gibt eine neue Option zum Steuern von Größenbeschränkungen für Nachrichten von Clients.There is a new option for controlling message size limits from clients. Gehen Sie beispielsweise in Startup.ConfigureServices
folgendermaßen vor:For example, in Startup.ConfigureServices
:
services.AddSignalR(hubOptions =>
{
hubOptions.MaximumReceiveMessageSize = 32768;
});
In ASP.net Core 2,2 konnten Sie die festlegen, die TransportMaxBufferSize
die maximale Nachrichtengröße effektiv steuern würde.In ASP.NET Core 2.2, you could set the TransportMaxBufferSize
and that would effectively control the maximum message size. In ASP.net Core 3,0 steuert diese Option jetzt nur die maximale Größe, bevor der Rückdruck festgestellt wird.In ASP.NET Core 3.0, that option now only controls the maximum size before backpressure is observed.
MVC-ControllerMVC controllers
Die Zuordnung von Controllern erfolgt nun in UseEndpoints
.Mapping of controllers now takes place inside UseEndpoints
.
Fügen Sie hinzu, MapControllers
Wenn die APP Attribut Routing verwendet.Add MapControllers
if the app uses attribute routing. Da das Routing Unterstützung für viele Frameworks in ASP.net Core 3,0 oder höher bietet, ist das Hinzufügen von Attribut Weiterleitungs Controllern ein Opt-in.Since routing includes support for many frameworks in ASP.NET Core 3.0 or later, adding attribute-routed controllers is opt-in.
Ersetzen Sie Folgendes:Replace the following:
MapRoute
mitMapControllerRoute
MapRoute
withMapControllerRoute
MapAreaRoute
mitMapAreaControllerRoute
MapAreaRoute
withMapAreaControllerRoute
Da das Routing nun die Unterstützung für mehr als nur MVC umfasst, hat sich die Terminologie geändert, damit diese Methoden deutlich erkennen können, was Sie tun.Since routing now includes support for more than just MVC, the terminology has changed to make these methods clearly state what they do. Herkömmliche Routen wie MapControllerRoute
/ MapAreaControllerRoute
/ MapDefaultControllerRoute
werden in der Reihenfolge angewendet, in der Sie hinzugefügt werden.Conventional routes such as MapControllerRoute
/MapAreaControllerRoute
/MapDefaultControllerRoute
are applied in the order that they're added. Platzieren Sie zunächst spezifischere Routen (z. b. Routen für einen Bereich).Place more specific routes (such as routes for an area) first.
Im folgenden Beispiel:In the following example:
MapControllers
Fügt Unterstützung für Attribut Weiterleitungs Controller hinzu.MapControllers
adds support for attribute-routed controllers.MapAreaControllerRoute
Fügt eine konventionelle Route für Controller in einem Bereich hinzu.MapAreaControllerRoute
adds a conventional route for controllers in an area.MapControllerRoute
Fügt eine konventionelle Route für Controller hinzu.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?}");
});
}
Asynchrones Suffix aus Controller-Aktions Namen entfernenAsync suffix removal from controller action names
In ASP.net Core 3,0 entfernt ASP.net Core MVC das Async
Suffix aus den Controller Aktions Namen.In ASP.NET Core 3.0, ASP.NET Core MVC removes the Async
suffix from controller action names. Das Routing und die Verknüpfungs Generierung sind von dieser neuen Standardeinstellung betroffen.Both routing and link generation are impacted by this new default. Beispiel:For example:
public class ProductsController : Controller
{
public async Task<IActionResult> ListAsync()
{
var model = await _dbContext.Products.ToListAsync();
return View(model);
}
}
Vor ASP.net Core 3,0:Prior to ASP.NET Core 3.0:
Auf die vorherige Aktion kann auf der Route " Products/listasync " zugegriffen werden.The preceding action could be accessed at the Products/ListAsync route.
Die Link Generierung erforderte das Angeben des Suffixes
Async
.Link generation required specifying theAsync
suffix. Beispiel:For example:<a asp-controller="Products" asp-action="ListAsync">List</a>
In ASP.net Core 3,0:In ASP.NET Core 3.0:
Auf die vorangehende Aktion kann auf der Route " Products/List " zugegriffen werden.The preceding action can be accessed at the Products/List route.
Bei der Link Generierung muss das Suffix nicht angegeben werden
Async
.Link generation doesn't require specifying theAsync
suffix. Beispiel:For example:<a asp-controller="Products" asp-action="List">List</a>
Diese Änderung wirkt sich nicht auf die mit dem-Attribut angegebenen Namen aus [ActionName]
.This change doesn't affect names specified using the [ActionName]
attribute. Das Standardverhalten kann mit dem folgenden Code in deaktiviert werden Startup.ConfigureServices
:The default behavior can be disabled with the following code in Startup.ConfigureServices
:
services.AddMvc(options =>
options.SuppressAsyncSuffixInActionNames = false);
Änderungen an der Link GenerierungChanges to link generation
Wie in der Dokumentation zu den unterschieden aus früheren Versionen des Routingserläutert, gibt es einige Unterschiede bei der Link Generierung ( Url.Link
z. b. mit und ähnlichen APIs).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). Dazu gehören:These include:
- Wenn Sie das Endpunkt Routing verwenden, wird die Groß-/Kleinschreibung von Routen Parametern in generierten URIs standardmäßig nicht zwangsläufig beibehalten.By default, when using endpoint routing, casing of route parameters in generated URIs is not necessarily preserved. Dieses Verhalten kann mit der-
IOutboundParameterTransformer
Schnittstelle gesteuert werden.This behavior can be controlled with theIOutboundParameterTransformer
interface. - Wenn Sie einen URI für eine ungültige Route generieren (ein Controller, eine Aktion oder eine Seite, die nicht vorhanden ist), wird unter Endpunkt Routing eine leere Zeichenfolge erstellt, anstatt einen ungültigen URI zu erzeugen.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-Werte (Routen Parameter aus dem aktuellen Kontext) werden bei der Link Generierung mit dem Endpunkt Routing nicht automatisch verwendet.Ambient values (route parameters from the current context) are not automatically used in link generation with endpoint routing. Zuvor wurden bei der Erstellung eines Links zu einer anderen Aktion (oder Seite) nicht angegebene Routen Werte von den aktuellen Routen Werten abgeleitet.Previously, when generating a link to another action (or page), unspecified route values would be inferred from the current routes ambient values. Bei Verwendung des Endpunkt Routings müssen alle Routen Parameter während der Link Generierung explizit angegeben werden.When using endpoint routing, all route parameters must be specified explicitly during link generation.
Razor PagesRazor Pages
Die Zuordnung von Razor Seiten erfolgt nun in UseEndpoints
.Mapping Razor Pages now takes place inside UseEndpoints
.
Fügen Sie hinzu, MapRazorPages
Wenn die APP Razor Seiten verwendet.Add MapRazorPages
if the app uses Razor Pages. Da das Endpunkt Routing Unterstützung für viele Frameworks umfasst, ist das Hinzufügen von Razor Seiten jetzt deaktiviert.Since Endpoint Routing includes support for many frameworks, adding Razor Pages is now opt-in.
In der folgenden Startup.Configure
Methode MapRazorPages
Fügt Unterstützung für Razor Seiten hinzu:In the following Startup.Configure
method, MapRazorPages
adds support for Razor Pages:
public void Configure(IApplicationBuilder app)
{
...
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
Verwenden von MVC ohne Endpunkt RoutingUse MVC without Endpoint Routing
Die Verwendung von MVC über UseMvc
oder UseMvcWithDefaultRoute
in ASP.net Core 3,0 erfordert ein explizites Opt-in in Startup.ConfigureServices
.Using MVC via UseMvc
or UseMvcWithDefaultRoute
in ASP.NET Core 3.0 requires an explicit opt-in inside Startup.ConfigureServices
. Dies ist erforderlich, da MVC wissen muss, ob es während der Initialisierung auf die Autorisierung und die cors-Middleware zurückgreifen kann.This is required because MVC must know whether it can rely on the authorization and CORS Middleware during initialization. Es wird ein Analyzer bereitgestellt, der warnt, wenn die APP versucht, eine nicht unterstützte Konfiguration zu verwenden.An analyzer is provided that warns if the app attempts to use an unsupported configuration.
Wenn die APP Legacy IRouter
Unterstützung erfordert, deaktivieren EnableEndpointRouting
Sie die Verwendung der folgenden Ansätze in Startup.ConfigureServices
:If 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);
IntegritätsprüfungenHealth checks
Integritätsprüfungen können als routerware mit Endpunkt Routing verwendet werden.Health checks can be used as a router-ware with Endpoint Routing.
Fügen Sie hinzu MapHealthChecks
, um Integritätsprüfungen mit Endpunkt Routing zu verwenden.Add MapHealthChecks
to use health checks with Endpoint Routing. Die- MapHealthChecks
Methode akzeptiert Argumente ähnlich wie UseHealthChecks
.The MapHealthChecks
method accepts arguments similar to UseHealthChecks
. Der Vorteil der Verwendung von MapHealthChecks
over UseHealthChecks
ist die Fähigkeit, Autorisierung anzuwenden und eine präzisere Kontrolle über die abgleichsrichtlinie zu haben.The advantage of using MapHealthChecks
over UseHealthChecks
is the ability to apply authorization and to have greater fine-grained control over the matching policy.
Im folgenden Beispiel MapHealthChecks
wird für einen Integritäts Prüf Punkt aufgerufen /healthz
:In 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() { });
});
}
Der hostbuilder ersetzt webhostbuilder.HostBuilder replaces WebHostBuilder
In den ASP.net Core 3,0-Vorlagen wird generischer Hostverwendet.The ASP.NET Core 3.0 templates use Generic Host. In früheren Versionen wurde Webhostverwendet.Previous versions used Web Host. Der folgende Code zeigt die von der ASP.net Core 3,0-Vorlage generierte Program
Klasse: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>();
});
}
Der folgende Code zeigt die von der Vorlage generierte ASP.net Core 2,2- Program
Klasse: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 verbleibt in 3,0 und ist der Typ von, der webBuilder
im vorangehenden Codebeispiel angezeigt wird.IWebHostBuilder remains in 3.0 and is the type of the webBuilder
seen in the preceding code sample. WebHostBuilder wird in einer zukünftigen Version als veraltet markiert und durch ersetzt HostBuilder
.WebHostBuilder will be deprecated in a future release and replaced by HostBuilder
.
Die signifikanteste Änderung von in WebHostBuilder
HostBuilder
ist die Abhängigkeitsinjektion (di).The most significant change from WebHostBuilder
to HostBuilder
is in dependency injection (DI). Wenn HostBuilder
Sie verwenden, können Sie nur den folgenden in Startup
den-Konstruktor einfügen:When using HostBuilder
, you can only inject the following into Startup
's constructor:
Die HostBuilder
di-Einschränkungen:The HostBuilder
DI constraints:
- Aktivieren Sie den di-Container nur ein einziges Mal.Enable the DI container to be built only one time.
- Vermeidet die resultierenden Probleme bei der Objekt Lebensdauer wie das Auflösen mehrerer Instanzen von Singletons.Avoids the resulting object lifetime issues like resolving multiple instances of singletons.
Weitere Informationen finden Sie unter vermeiden der Start Dienst Injektion in ASP.net Core 3.For more information, see Avoiding Startup service injection in ASP.NET Core 3.
Addauthorization in eine andere Assembly verschobenAddAuthorization moved to a different assembly
Die Methoden ASP.net Core 2,2 und niedriger AddAuthorization
in Microsoft.AspNetCore.Authorization.dll:The ASP.NET Core 2.2 and lower AddAuthorization
methods in Microsoft.AspNetCore.Authorization.dll:
- Wurden umbenannt
AddAuthorizationCore
.Have been renamedAddAuthorizationCore
. - Wurden in Microsoft.AspNetCore.Authorization.Policy.dll verschoben.Have been moved to Microsoft.AspNetCore.Authorization.Policy.dll.
Apps, die sowohl Microsoft.AspNetCore.Authorization.dll als auch Microsoft.AspNetCore.Authorization.Policy.dll verwenden, sind nicht betroffen.Apps that are using both Microsoft.AspNetCore.Authorization.dll and Microsoft.AspNetCore.Authorization.Policy.dll aren't impacted.
Apps, die Microsoft.AspNetCore.Authorization.Policy.dll nicht verwenden, sollten eine der folgenden Aktionen ausführen:Apps that are not using Microsoft.AspNetCore.Authorization.Policy.dll should do one of the following:
- Fügen Sie einen Verweis auf Microsoft.AspNetCore.Authorization.Policy.dll hinzu.Add a reference to Microsoft.AspNetCore.Authorization.Policy.dll. Diese Vorgehensweise funktioniert für die meisten apps und ist alles, was erforderlich ist.This approach works for most apps and is all that is required.
- Wechseln zu mithilfe von
AddAuthorizationCore
Switch to usingAddAuthorizationCore
Weitere Informationen finden Sie unter Breaking Change in (Breaking Change in AddAuthorization(o =>
) der Überlastung in einer anderen Assembly #386.For more information, see Breaking change in AddAuthorization(o =>
) overload lives in a different assembly #386.
Benutzeroberfläche von IdentityIdentity UI
Identity Aktualisierungen der Benutzeroberfläche für ASP.net Core 3,0:Identity UI updates for ASP.NET Core 3.0:
- Fügen Sie einen Paket Verweis auf Microsoft. aspnetcore hinzu. Identity Benutzeroberfläche.Add a package reference to Microsoft.AspNetCore.Identity.UI.
- Apps, die keine Razor Seiten verwenden, müssen aufruft
MapRazorPages
.Apps that don't use Razor Pages must callMapRazorPages
. Siehe Razor Seiten in diesem Dokument.See Razor Pages in this document. - Bootstrap 4 ist das Standard Framework für die Benutzeroberfläche.Bootstrap 4 is the default UI framework. Legen
IdentityUIFrameworkVersion
Sie eine Projekt Eigenschaft fest, um die Standardeinstellung zu ändern.Set anIdentityUIFrameworkVersion
project property to change the default. Weitere Informationen finden Sie in dieser GitHub-Ankündigung.For more information, see this GitHub announcement.
SignalR
Der SignalR JavaScript-Client wurde von @aspnet/signalr
in geändert @microsoft/signalr
.The SignalR JavaScript client has changed from @aspnet/signalr
to @microsoft/signalr
. Um auf diese Änderung zu reagieren, ändern Sie die Verweise in package.jsfür Dateien, require
Anweisungen und ECMAScript- import
Anweisungen.To react to this change, change the references in package.json files, require
statements, and ECMAScript import
statements.
System.Text.Json ist das Standardprotokoll.System.Text.Json is the default protocol
System.Text.Json
ist nun das Standardhub Protokoll, das sowohl vom Client als auch vom Server verwendet wird.System.Text.Json
is now the default Hub protocol used by both the client and server.
In Startup.ConfigureServices
wird aufgerufen, AddJsonProtocol
um Serialisierungsoptionen festzulegen.In Startup.ConfigureServices
, call AddJsonProtocol
to set serializer options.
ServersServer:
services.AddSignalR(...)
.AddJsonProtocol(options =>
{
options.PayloadSerializerOptions.WriteIndented = false;
})
Client:Client:
new HubConnectionBuilder()
.WithUrl("/chathub")
.AddJsonProtocol(options =>
{
options.PayloadSerializerOptions.WriteIndented = false;
})
.Build();
Zum Newtonsoft.JswechselnSwitch to Newtonsoft.Json
Wenn Sie Features von Newtonsoft.Json verwenden, die in System.Text.Jsnicht unterstütztwerden, können Sie zurück zu wechseln Newtonsoft.Json
.If you're using features of Newtonsoft.Json that aren't supported in System.Text.Json, you can switch back to Newtonsoft.Json
. Weitere Informationen finden Sie weiter oben in diesem Artikel unter Verwenden von Newtonsoft.Jsin einem ASP.net Core 3,0- SignalR Projekt .See Use Newtonsoft.Json in an ASP.NET Core 3.0 SignalR project earlier in this article.
Verteilte redis-CachesRedis distributed caches
Das Microsoft. Extensions. Caching. redis -Paket ist für 3,0 ASP.net Core-Apps oder höher nicht verfügbar.The Microsoft.Extensions.Caching.Redis package isn't available for ASP.NET Core 3.0 or later apps. Ersetzen Sie den Paket Verweis durch Microsoft. Extensions. Caching. stackexchangeredis.Replace the package reference with Microsoft.Extensions.Caching.StackExchangeRedis. Weitere Informationen finden Sie unter Verteiltes Zwischenspeichern in ASP.net Core.For more information, see Verteiltes Zwischenspeichern in ASP.net Core.
Abonnieren der Lauf Zeit KompilierungOpt in to runtime compilation
Vor ASP.net Core 3,0 war die Lauf Zeit Kompilierung von Sichten eine implizite Funktion des Frameworks.Prior to ASP.NET Core 3.0, runtime compilation of views was an implicit feature of the framework. Die Lauf Zeit Kompilierung ergänzt die Kompilierung der Erstellung von Sichten.Runtime compilation supplements build-time compilation of views. Dadurch kann das Framework Razor Sichten und Seiten (cshtml -Dateien) kompilieren, wenn die Dateien geändert werden, ohne dass die gesamte APP neu erstellt werden muss.It allows the framework to compile Razor views and pages (.cshtml files) when the files are modified, without having to rebuild the entire app. Diese Funktion unterstützt das Szenario der schnellen Bearbeitung in der IDE und das Aktualisieren des Browsers, um die Änderungen anzuzeigen.This feature supports the scenario of making a quick edit in the IDE and refreshing the browser to view the changes.
In ASP.net Core 3,0 ist die Lauf Zeit Kompilierung ein Opt-in-Szenario.In ASP.NET Core 3.0, runtime compilation is an opt-in scenario. Die Kompilierzeit Kompilierung ist der einzige Mechanismus zum Anzeigen der Kompilierung, der standardmäßig aktiviert ist.Build-time compilation is the only mechanism for view compilation that's enabled by default. Die Laufzeit basiert auf Visual Studio oder dotnet-Watch in Visual Studio Code, um das Projekt neu zu erstellen, wenn Änderungen an cshtml -Dateien erkannt werden.The runtime relies on Visual Studio or dotnet-watch in Visual Studio Code to rebuild the project when it detects changes to .cshtml files. In Visual Studio werden Änderungen an den CS- , cshtml-oder Razor -Dateien im Projekt, das ausgeführt wird (STRG + F5), aber nicht debuggt (F5), die Neukompilierung des Projekts auslöst.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.
So aktivieren Sie die Lauf Zeit Kompilierung in Ihrem ASP.net Core 3,0-Projekt:To enable runtime compilation in your ASP.NET Core 3.0 project:
Installieren Sie Microsoft. aspnetcore. MVC. Razor . Runtimecompilation -nuget-Paket.Install the Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation NuGet package.
Update
Startup.ConfigureServices
zum aufzurufenAddRazorRuntimeCompilation
:UpdateStartup.ConfigureServices
to callAddRazorRuntimeCompilation
:Verwenden Sie für ASP.net Core MVC den folgenden Code:For ASP.NET Core MVC, use the following code:
services.AddControllersWithViews() .AddRazorRuntimeCompilation(...);
Verwenden Sie für ASP.net Core Razor Seiten den folgenden Code:For ASP.NET Core Razor Pages, use the following code:
services.AddRazorPages() .AddRazorRuntimeCompilation(...);
Das Beispiel unter https://github.com/aspnet/samples/tree/master/samples/aspnetcore/mvc/runtimecompilation zeigt ein Beispiel für die bedingte Aktivierung der Lauf Zeit Kompilierung in Entwicklungsumgebungen.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.
Weitere Informationen zur Razor Kompilierung von Dateien finden Sie unter Razor Datei Kompilierung in ASP.net Core .For more information on Razor file compilation, see Razor Datei Kompilierung in ASP.net Core.
Migrieren von Bibliotheken mithilfe der ZielplattformMigrate libraries via multi-targeting
Bibliotheken müssen häufig mehrere Versionen von ASP.net Core unterstützen.Libraries often need to support multiple versions of ASP.NET Core. Die meisten Bibliotheken, die für frühere Versionen von ASP.net Core kompiliert wurden, sollten ohne Probleme weiterhin funktionieren.Most libraries that were compiled against previous versions of ASP.NET Core should continue working without issues. Die folgenden Bedingungen erfordern eine Kreuz Kompilierung der APP:The following conditions require the app to be cross-compiled:
- Die Bibliothek basiert auf einer Funktion, die über eine binäre Breaking Changeverfügt.The library relies on a feature that has a binary breaking change.
- Die Bibliothek möchte die neuen Features in ASP.net Core 3,0 nutzen.The library wants to take advantage of new features in ASP.NET Core 3.0.
Beispiel: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>
Verwenden #ifdefs
Sie, um ASP.net Core 3,0-spezifische APIs zu aktivieren: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
Weitere Informationen zum Verwenden von ASP.net Core-APIs in einer Klassenbibliothek finden Sie unter Verwenden von ASP.NET Core-APIs in einer Klassenbibliothek .For more information on using ASP.NET Core APIs in a class library, see Verwenden von ASP.NET Core-APIs in einer Klassenbibliothek.
Verschiedene ÄnderungenMiscellaneous changes
Das Validierungssystem in .NET Core 3.0 und höher behandelt Non-Nullable-Parameter oder gebundene Eigenschaften so, als würden sie ein [Required]
-Attribut aufweisen.The validation system in .NET Core 3.0 and later treats non-nullable parameters or bound properties as if they had a [Required]
attribute. Weitere Informationen finden Sie unter [Required]-Attribut.For more information, see [Required] attribute.
VeröffentlichenPublish
Löschen Sie die Ordner " bin " und " obj " im Projektverzeichnis.Delete the bin and obj folders in the project directory.
TestServerTestServer
Erstellen Sie für apps, die TestServer direkt mit dem generischen Hostverwendet werden, TestServer
auf einem IWebHostBuilder in ConfigureWebHost :For 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);
}
Wichtige API-ÄnderungenBreaking API changes
Wichtige Änderungen überprüfen:Review breaking changes:
- Umfassende Liste der wichtigen Änderungen in der Version ASP.net Core 3,0Complete list of breaking changes in the ASP.NET Core 3.0 release
- Unterbrechen von API-Änderungen in Antifälschung, cors, Diagnose, MVC und Routing.Breaking API changes in Antiforgery, CORS, Diagnostics, MVC, and Routing. Diese Liste enthält Breaking Changes für Kompatibilitätsoptionen.This list includes breaking changes for compatibility switches.
- Eine Zusammenfassung 2,2-zu-3,0-Änderungen in .net Core, ASP.net Core und Entity Framework Core finden Sie unter Breaking Changes for Migration from Version 2,2 to 3,0.For a summary of 2.2-to-3.0 breaking changes across .NET Core, ASP.NET Core, and Entity Framework Core, see Breaking changes for migration from version 2.2 to 3.0.
Endpunkt Routing mit Catch-All-ParameterEndpoint routing with catch-all parameter
Warnung
Ein catch-all-Parameter kann aufgrund eines Fehlers beim Routing nicht ordnungsgemäß mit Routen übereinstimmen.A catch-all parameter may match routes incorrectly due to a bug in routing. Apps, die von diesem Fehler betroffen sind, weisen die folgenden Merkmale auf:Apps impacted by this bug have the following characteristics:
- Eine catch-all-Route, zum Beispiel
{**slug}"
A catch-all route, for example,{**slug}"
- Die catch-all-Route kann nicht mit Anforderungen abgeglichen werden, die abgeglichen werden sollen.The catch-all route fails to match requests it should match.
- Durch das Entfernen anderer Routen funktioniert die catch-all-Route.Removing other routes makes catch-all route start working.
Weitere Beispiele zu diesem Fehler finden Sie in den GitHub-Issues 18677 und 16579.See GitHub bugs 18677 and 16579 for example cases that hit this bug.
Eine Opt-in-Behebung für diesen Fehler ist im .NET Core 3.1.301 SDK und höher enthalten.An opt-in fix for this bug is contained in .NET Core 3.1.301 SDK and later. Der folgende Code legt einen internen Switch fest, mit dem dieser Fehler behoben wird: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.
.Net Core 3,0 auf Azure App Service.NET Core 3.0 on Azure App Service
Das Rollout von .net Core auf Azure App Service ist abgeschlossen.The rollout of .NET Core to Azure App Service is finished. .Net Core 3,0 ist in allen Azure App Service Rechenzentren verfügbar..NET Core 3.0 is available in all Azure App Service datacenters.