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

本文重点介绍 ASP.NET Core 3.0 中最重要的更改,并提供相关文档的链接。This article highlights the most significant changes in ASP.NET Core 3.0 with links to relevant documentation.

[Blazor

[Blazor 是 ASP.NET Core 中的新框架,用于使用 .NET 生成交互式客户端 Web UI:[Blazor is a new framework in ASP.NET Core for building interactive client-side web UI with .NET:

  • 使用 C# 代替 JavaScript 来创建丰富的交互式 UI。Create rich interactive UIs using C# instead of JavaScript.
  • 共享使用 .NET 编写的服务器端和客户端应用逻辑。Share server-side and client-side app logic written in .NET.
  • 将 UI 呈现为 HTML 和 CSS,以支持众多浏览器,其中包括移动浏览器。Render the UI as HTML and CSS for wide browser support, including mobile browsers.

[Blazor 框架支持的方案:[Blazor framework supported scenarios:

  • 可重用的 UI 组件([Razor 组件)Reusable UI components ([Razor components)
  • 客户端路由Client-side routing
  • 组件布局Component layouts
  • 对依赖项注入的支持Support for dependency injection
  • 窗体和验证Forms and validation
  • 用 [Razor 类库构建组件库Build component libraries with [Razor class libraries
  • JavaScript 互操作JavaScript interop

有关详细信息,请参阅 ASP.NET Core Blazor 简介For more information, see ASP.NET Core Blazor 简介.

[Blazor Server

[Blazor 将组件呈现逻辑从 UI 更新的应用方式中分离出来。[Blazor decouples component rendering logic from how UI updates are applied. [Blazor Server在 ASP.NET Core 应用中支持在服务器上托管 [Razor 组件。[Blazor Server provides support for hosting [Razor components on the server in an ASP.NET Core app. 可通过 [SignalR 连接处理 UI 更新。UI updates are handled over a [SignalR connection. ASP.NET Core 3.0 支持 [Blazor Server。[Blazor Server is supported in ASP.NET Core 3.0.

[Blazor WebAssembly(预览版)[Blazor WebAssembly (Preview)

还可以使用基于 WebAssembly 的 .NET 运行时直接在浏览器中运行 [Blazor 应用。[Blazor apps can also be run directly in the browser using a WebAssembly-based .NET runtime. [Blazor WebAssembly 处于预览版阶段,ASP.NET Core 3.0 不提供支持。[Blazor WebAssembly is in preview and not supported in ASP.NET Core 3.0. ASP.NET Core 的未来版本将支持 [Blazor WebAssembly。[Blazor WebAssembly will be supported in a future release of ASP.NET Core.

[Razor 组件[Razor components

[Blazor 应用是基于组件构建的。[Blazor apps are built from components. 组件是自包含的用户界面 (UI) 块,例如页、对话框或窗体。Components are self-contained chunks of user interface (UI), such as a page, dialog, or form. 组件是定义 UI 呈现逻辑和客户端事件处理程序的普通 .NET 类。Components are normal .NET classes that define UI rendering logic and client-side event handlers. 无需 JavaScript 即可创建丰富的交互式 Web 应用。You can create rich interactive web apps without JavaScript.

通常使用 [Razor 语法(HTML 和 C# 的自然混合)创建 [Blazor 中的组件。Components in [Blazor are typically authored using [Razor syntax, a natural blend of HTML and C#. [Razor 组件与 [Razor Pages 和 MVC 视图类似,因为它们都使用 [Razor。[Razor components are similar to [Razor Pages and MVC views in that they both use [Razor. 与基于请求-响应模型的页和视图不同,组件专门用于处理 UI 构成。Unlike pages and views, which are based on a request-response model, components are used specifically for handling UI composition.

gRPCgRPC

gRPCgRPC:

  • 是一个流行的高性能 RPC(远程过程调用)框架。Is a popular, high-performance RPC (remote procedure call) framework.

  • 提供固定的协定优先方法进行 API 开发。Offers an opinionated contract-first approach to API development.

  • 使用的新式技术如下:Uses modern technologies such as:

    • 用于传输的 HTTP/2。HTTP/2 for transport.
    • 作为接口描述语言的协议缓冲区。Protocol Buffers as the interface description language.
    • 二进制序列化格式。Binary serialization format.
  • 提供如下功能:Provides features such as:

    • 身份验证Authentication
    • 双向流式处理和流控制。Bidirectional streaming and flow control.
    • 取消和超时。Cancellation and timeouts.

ASP.NET Core 3.0 中的 gRPC 功能包括:gRPC functionality in ASP.NET Core 3.0 includes:

  • Grpc.AspNetCore:用于托管 gRPC 服务的 ASP.NET Core 框架。Grpc.AspNetCore: An ASP.NET Core framework for hosting gRPC services. ASP.NET Core 上的 gRPC 与标准 ASP.NET Core 功能(例如日志记录、依赖关系注入 (DI)、身份验证和授权)集成。gRPC on ASP.NET Core integrates with standard ASP.NET Core features like logging, dependency injection (DI), authentication, and authorization.
  • Grpc.Net.Client:基于熟悉的 HttpClient 构建的 .NET Core 的 gRPC 客户端。Grpc.Net.Client: A gRPC client for .NET Core that builds upon the familiar HttpClient.
  • Grpc.Net.ClientFactory:gRPC 客户端与 HttpClientFactory 的集成。Grpc.Net.ClientFactory: gRPC client integration with HttpClientFactory.

有关详细信息,请参阅 .NET Core 上的 gRPC 的简介For more information, see .NET Core 上的 gRPC 的简介.

[SignalR

有关迁移说明,请参阅更新 代码[SignalR。See [Update SignalR code for migration instructions. [SignalR 现在使用 System.Text.Json 来序列化/反序列化 JSON 消息。[SignalR now uses System.Text.Json to serialize/deserialize JSON messages. 有关还原基于 Newtonsoft.Json 的序列化程序的说明,请参阅切换到 Newtonsoft.JsonSee Switch to Newtonsoft.Json for instructions to restore the Newtonsoft.Json-based serializer.

在 [SignalR 的 JavaScript 和 .NET 客户端中,添加了自动重新连接支持。In the JavaScript and .NET Clients for [SignalR, support was added for automatic reconnection. 默认情况下,客户端会立即尝试重新连接,并根据需要分别在 2 秒、10 秒和 30 秒后重试。By default, the client tries to reconnect immediately and retry after 2, 10, and 30 seconds if necessary. 如果客户端成功重新连接,则会收到新的连接 ID。If the client successfully reconnects, it receives a new connection ID. 选择启用自动重新连接:Automatic reconnect is opt-in:

const connection = new signalR.HubConnectionBuilder()
    .withUrl("/chathub")
    .withAutomaticReconnect()
    .build();

可以通过传递基于毫秒的持续时间数组来指定重新连接间隔:The reconnection intervals can be specified by passing an array of millisecond-based durations:

.withAutomaticReconnect([0, 3000, 5000, 10000, 15000, 30000])
//.withAutomaticReconnect([0, 2000, 10000, 30000]) The default intervals.

可以通过传入自定义实现来完全控制重新连接间隔。A custom implementation can be passed in for full control of the reconnection intervals.

如果在上一次重新连接间隔后重新连接失败:If the reconnection fails after the last reconnect interval:

  • 客户端认为连接处于脱机状态。The client considers the connection is offline.
  • 客户端将停止尝试重新连接。The client stops trying to reconnect.

尝试重新连接时,更新应用 UI,通知用户正在尝试重新连接。During reconnection attempts, update the app UI to notify the user that the reconnection is being attempted.

为了在连接中断时提供 UI 反馈,[SignalR 客户端 API 已扩展为包含以下事件处理程序:To provide UI feedback when the connection is interrupted, the [SignalR client API has been expanded to include the following event handlers:

  • onreconnecting:使开发人员有机会禁用 UI 或允许用户了解应用程序处于脱机状态。onreconnecting: Gives developers an opportunity to disable UI or to let users know the app is offline.
  • onreconnected:使开发人员有机会在重新建立连接后更新 UI。onreconnected: Gives developers an opportunity to update the UI once the connection is reestablished.

以下代码在尝试连接时使用 onreconnecting 更新 UI:The following code uses onreconnecting to update the UI while trying to connect:

connection.onreconnecting((error) => {
    const status = `Connection lost due to error "${error}". Reconnecting.`;
    document.getElementById("messageInput").disabled = true;
    document.getElementById("sendButton").disabled = true;
    document.getElementById("connectionStatus").innerText = status;
});

以下代码在连接时使用 onreconnected 更新 UI:The following code uses onreconnected to update the UI on connection:

connection.onreconnected((connectionId) => {
    const status = `Connection reestablished. Connected.`;
    document.getElementById("messageInput").disabled = false;
    document.getElementById("sendButton").disabled = false;
    document.getElementById("connectionStatus").innerText = status;
});

当中心方法要求授权时,[SignalR 3.0 和更高版本为授权处理程序提供了一个自定义资源。[SignalR 3.0 and later provides a custom resource to authorization handlers when a hub method requires authorization. 资源是 HubInvocationContext 的一个实例。The resource is an instance of HubInvocationContext. HubInvocationContext 包括:The HubInvocationContext includes the:

  • HubCallerContext
  • 正在调用的中心方法的名称。Name of the hub method being invoked.
  • 中心方法的参数。Arguments to the hub method.

请考虑以下通过 Azure Active Directory 允许多个组织登录的聊天室应用示例。Consider the following example of a chat room app allowing multiple organization sign-in via Azure Active Directory. 拥有 Microsoft 帐户的任何人都可以登录到聊天,但只有所属组织的成员才能阻止用户或查看用户的聊天历史记录。Anyone with a Microsoft account can sign in to chat, but only members of the owning organization can ban users or view users' chat histories. 该应用可以限制特定用户的某些功能。The app could restrict certain functionality from specific users.

public class DomainRestrictedRequirement :
    AuthorizationHandler<DomainRestrictedRequirement, HubInvocationContext>,
    IAuthorizationRequirement
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
        DomainRestrictedRequirement requirement,
        HubInvocationContext resource)
    {
        if (context.User?.[Identity?.Name == null)
        {
            return Task.CompletedTask;
        }

        if (IsUserAllowedToDoThis(resource.HubMethodName, context.User.[Identity.Name))
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }

    private bool IsUserAllowedToDoThis(string hubMethodName, string currentUsername)
    {
        if (hubMethodName.Equals("banUser", StringComparison.OrdinalIgnoreCase))
        {
            return currentUsername.Equals("bob42@jabbr.net", StringComparison.OrdinalIgnoreCase);
        }

        return currentUsername.EndsWith("@jabbr.net", StringComparison.OrdinalIgnoreCase));
    }
}

在前面的代码中,DomainRestrictedRequirement 作为自定义 IAuthorizationRequirementIn the preceding code, DomainRestrictedRequirement serves as a custom IAuthorizationRequirement. 由于正在传入 HubInvocationContext 资源参数,因此内部逻辑可以:Because the HubInvocationContext resource parameter is being passed in, the internal logic can:

  • 检查在其中调用中心的上下文。Inspect the context in which the Hub is being called.
  • 做出允许用户执行单个中心方法的决策。Make decisions on allowing the user to execute individual Hub methods.

可以通过代码在运行时检查的策略的名称来标记单个中心方法。Individual Hub methods can be marked with the name of the policy the code checks at run-time. 当客户端尝试调用单个中心方法时,DomainRestrictedRequirement 处理程序将运行并控制对方法的访问。As clients attempt to call individual Hub methods, the DomainRestrictedRequirement handler runs and controls access to the methods. 基于 DomainRestrictedRequirement 控制访问的方式:Based on the way the DomainRestrictedRequirement controls access:

  • 所有已登录的用户都可以调用 SendMessage 方法。All logged-in users can call the SendMessage method.
  • 只有使用 @jabbr.net 电子邮件地址登录的用户才能查看用户的历史记录。Only users who have logged in with a @jabbr.net email address can view users' histories.
  • 只有 bob42@jabbr.net 才能阻止用户进入聊天室。Only bob42@jabbr.net can ban users from the chat room.
[Authorize]
public class ChatHub : Hub
{
    public void SendMessage(string message)
    {
    }

    [Authorize("DomainRestricted")]
    public void BanUser(string username)
    {
    }

    [Authorize("DomainRestricted")]
    public void ViewUserHistory(string username)
    {
    }
}

创建 DomainRestricted 策略可能涉及:Creating the DomainRestricted policy might involve:

  • 在 Startup.cs 中,添加新策略。In Startup.cs, adding the new policy.
  • 提供自定义 DomainRestrictedRequirement 要求作为参数。Provide the custom DomainRestrictedRequirement requirement as a parameter.
  • 向授权中间件注册 DomainRestrictedRegistering DomainRestricted with the authorization middleware.
services
    .AddAuthorization(options =>
    {
        options.AddPolicy("DomainRestricted", policy =>
        {
            policy.Requirements.Add(new DomainRestrictedRequirement());
        });
    });

[SignalR 中心使用终结点路由[SignalR hubs use Endpoint Routing. 以前 [SignalR 中心连接是显式完成的:[SignalR hub connection was previously done explicitly:

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

在以前的版本中,开发人员需要将控制器、[Razor 页面和中心连接到各种位置。In the previous version, developers needed to wire up controllers, [Razor pages, and hubs in a variety of places. 显式连接会生成一系列几乎相同的路由段:Explicit connection results in a series of nearly-identical routing segments:

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

app.UseRouting(routes =>
{
    routes.MapRazorPages();
});

可以通过终结点路由来路由 [SignalR 3.0 中心。[SignalR 3.0 hubs can be routed via endpoint routing. 通过终结点路由,通常可以在 UseRouting 中配置所有路由:With endpoint routing, typically all routing can be configured in UseRouting:

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

ASP.NET Core 3.0 [SignalR 添加了:ASP.NET Core 3.0 [SignalR added:

客户端到服务器的流式处理。Client-to-server streaming. 使用客户端到服务器的流式处理时,服务器端方法可以获取 IAsyncEnumerable<T>ChannelReader<T> 的实例。With client-to-server streaming, server-side methods can take instances of either an IAsyncEnumerable<T> or ChannelReader<T>. 在下面的 C# 示例中,中心上的 UploadStream 方法将从客户端接收字符串流:In the following C# sample, the UploadStream method on the Hub will receive a stream of strings from the client:

public async Task UploadStream(IAsyncEnumerable<string> stream)
{
    await foreach (var item in stream)
    {
        // process content
    }
}

.NET 客户端应用程序可以将 IAsyncEnumerable<T>ChannelReader<T> 实例作为上述 UploadStream 中心方法的 stream 参数传递。.NET client apps can pass either an IAsyncEnumerable<T> or ChannelReader<T> instance as the stream argument of the UploadStream Hub method above.

for 循环完成并且本地函数退出后,将发送流完成:After the for loop has completed and the local function exits, the stream completion is sent:

async IAsyncEnumerable<string> clientStreamData()
{
    for (var i = 0; i < 5; i++)
    {
        var data = await FetchSomeData();
        yield return data;
    }
}

await connection.SendAsync("UploadStream", clientStreamData());

JavaScript 客户端应用将 [SignalR Subject(或 RxJS 主题)用于上面的 UploadStream 中心方法的 stream 参数。JavaScript client apps use the [SignalR Subject (or an RxJS Subject) for the stream argument of the UploadStream Hub method above.

let subject = new signalR.Subject();
await connection.send("StartStream", "MyAsciiArtStream", subject);

当字符串被捕获并准备发送给服务器时,JavaScript 代码可以使用 subject.next 方法处理字符串。The JavaScript code could use the subject.next method to handle strings as they are captured and ready to be sent to the server.

subject.next("example");
subject.complete();

使用类似于上述两个代码片段的代码,可创建实时流式处理体验。Using code like the two preceding snippets, real-time streaming experiences can be created.

新的 JSON 序列化New JSON serialization

ASP.NET Core 3.0 现在默认使用 System.Text.Json 进行 JSON 序列化:ASP.NET Core 3.0 now uses System.Text.Json by default for JSON serialization:

  • 以异步方式读取和写入 JSON。Reads and writes JSON asynchronously.
  • 针对 UTF-8 文本进行了优化。Is optimized for UTF-8 text.
  • 通常比 Newtonsoft.Json 性能更高。Typically higher performance than Newtonsoft.Json.

若要将 Json.NET 添加到 ASP.NET Core 3.0,请参阅添加基于 Newtonsoft.Json 的 JSON 格式支持To add Json.NET to ASP.NET Core 3.0, see Add Newtonsoft.Json-based JSON format support.

新的 [Razor 指令New [Razor directives

下面的列表包含新的 [Razor 指令:The following list contains new [Razor directives:

  • @attribute@attribute 指令将给定的属性应用于生成的页或视图的类。@attribute: The @attribute directive applies the given attribute to the class of the generated page or view. 例如 @attribute [Authorize]For example, @attribute [Authorize].
  • @implements@implements 指令为生成的类实现接口。@implements: The @implements directive implements an interface for the generated class. 例如 @implements IDisposableFor example, @implements IDisposable.

IdentityServer4 支持 Web API 和 SPA 的身份验证和授权IdentityServer4 supports authentication and authorization for web APIs and SPAs

ASP.NET Core 3.0 使用 Web API 授权的支持在单页应用 (SPA) 中提供身份验证。ASP.NET Core 3.0 offers authentication in Single Page Apps (SPAs) using the support for web API authorization. 用于验证和存储用户身份信息的 ASP.NET Core [Identity 与用于实现 Open ID Connect 的 IdentityServer4 结合使用。ASP.NET Core [Identity for authenticating and storing users is combined with IdentityServer4 for implementing Open ID Connect.

IdentityServer4 是适用于 ASP.NET Core 3.0 的 OpenID Connect 和 OAuth 2.0 框架。IdentityServer4 is an OpenID Connect and OAuth 2.0 framework for ASP.NET Core 3.0. 它提供了以下安全功能:It enables the following security features:

  • 身份验证即服务 (AaaS)Authentication as a Service (AaaS)
  • 跨多个应用程序类型的单一登录/注销 (SSO)Single sign-on/off (SSO) over multiple application types
  • API 的访问控制Access control for APIs
  • Federation GatewayFederation Gateway

有关详细信息,请参阅 IdentityServer4 文档SPA 的身份验证和授权For more information, see the IdentityServer4 documentation or Authentication and authorization for SPAs.

证书和 Kerberos 身份验证Certificate and Kerberos authentication

证书身份验证需要:Certificate authentication requires:

  • 将服务器配置为接受证书。Configuring the server to accept certificates.
  • Startup.Configure 中添加身份验证中间件。Adding the authentication middleware in Startup.Configure.
  • 将证书身份验证服务添加到 Startup.ConfigureServicesAdding the certificate authentication service in Startup.ConfigureServices.
public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(
        CertificateAuthenticationDefaults.AuthenticationScheme)
            .AddCertificate();
    // Other service configuration removed.
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseAuthentication();
    // Other app configuration removed.
}

用于证书身份验证的选项包括执行以下操作的能力:Options for certificate authentication include the ability to:

  • 接受自签名证书。Accept self-signed certificates.
  • 检查证书吊销。Check for certificate revocation.
  • 检查提供证书中是否有正确的使用标志。Check that the proffered certificate has the right usage flags in it.

默认的用户主体是从证书属性构造的。A default user principal is constructed from the certificate properties. 用户主体包含允许补充或替换主体的事件。The user principal contains an event that enables supplementing or replacing the principal. 有关详细信息,请参阅 在 ASP.NET Core 中配置证书身份验证For more information, see 在 ASP.NET Core 中配置证书身份验证.

Windows 身份验证已扩展到 Linux 和 macOS。Windows Authentication has been extended onto Linux and macOS. 在以前的版本中,Windows 身份验证限制为 IISHttpSysIn previous versions, Windows Authentication was limited to IIS and HttpSys. 在 ASP.NET Core 3.0 中,Kestrel 能够在 Windows、Linux 和 macOS 上对已加入 Windows 域的主机使用 Negotiate、KerberosNTLMIn ASP.NET Core 3.0, Kestrel has the ability to use Negotiate, Kerberos, and NTLM on Windows, Linux, and macOS for Windows domain-joined hosts. Kestrel 对这些身份验证方案的支持由 Microsoft.AspNetCore.Authentication.Negotiate NuGet 包提供。Kestrel support of these authentication schemes is provided by the Microsoft.AspNetCore.Authentication.Negotiate NuGet package. 对于其他身份验证服务,请配置身份验证应用范围,然后配置服务:As with the other authentication services, configure authentication app wide, then configure the service:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
        .AddNegotiate();
    // Other service configuration removed.
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseAuthentication();
    // Other app configuration removed.
}

主机要求:Host requirements:

  • Windows 主机必须将主体名称 (SPN) 添加到托管应用的用户帐户。Windows hosts must have Service Principal Names (SPNs) added to the user account hosting the app.
  • Linux 和 macOS 计算机必须加入域。Linux and macOS machines must be joined to the domain.
    • 必须为 Web 进程创建 SPN。SPNs must be created for the web process.
    • 必须在主机上生成并配置 Keytab 文件Keytab files must be generated and configured on the host machine.

有关详细信息,请参阅 在 ASP.NET Core 中配置 Windows 身份验证For more information, see 在 ASP.NET Core 中配置 Windows 身份验证.

模板更改Template changes

Web UI 模板([Razor Pages、具有控制器和视图的 MVC)已删除以下内容:The web UI templates ([Razor Pages, MVC with controller and views) have the following removed:

Angular 模板已更新,以便使用 Angular 8。The Angular template updated to use Angular 8.

默认情况下,[Razor 类库 (RCL) 模板默认为 [Razor 组件开发。The [Razor class library (RCL) template defaults to [Razor component development by default. Visual Studio 中的新模板选项提供了对页面和视图的模板支持。A new template option in Visual Studio provides template support for pages and views. 在命令行界面中通过模板创建 RCL 时,请传递 --support-pages-and-views 选项 (dotnet new razorclasslib --support-pages-and-views)。When creating an RCL from the template in a command shell, pass the --support-pages-and-views option (dotnet new razorclasslib --support-pages-and-views).

泛型主机Generic Host

ASP.NET Core 3.0 模板使用 .NET 通用主机The ASP.NET Core 3.0 templates use .NET 通用主机. 以前版本使用 WebHostBuilderPrevious versions used WebHostBuilder. 使用 .NET Core 泛型主机 (HostBuilder) 可以更好地将 ASP.NET Core 应用与非 Web 特定的其他服务器方案集成。Using the .NET Core Generic Host (HostBuilder) provides better integration of ASP.NET Core apps with other server scenarios that aren't web-specific. 有关详细信息,请参阅 HostBuilder 替换 WebHostBuilderFor more information, see HostBuilder replaces WebHostBuilder.

主机配置Host configuration

在 ASP.NET Core 3.0 版本之前,为 Web 主机的主机配置加载了前缀为 ASPNETCORE_ 的环境变量。Prior to the release of ASP.NET Core 3.0, environment variables prefixed with ASPNETCORE_ were loaded for host configuration of the Web Host. 在 3.0 中,对于带有 CreateDefaultBuilder 的主机配置,使用 AddEnvironmentVariables 加载以 DOTNET_ 为前缀的环境变量。In 3.0, AddEnvironmentVariables is used to load environment variables prefixed with DOTNET_ for host configuration with CreateDefaultBuilder.

对启动构造函数注入的更改Changes to Startup constructor injection

泛型主机仅支持以下类型的 Startup 构造函数注入:The Generic Host only supports the following types for Startup constructor injection:

所有服务仍可以直接作为 Startup.Configure 方法的参数注入。All services can still be injected directly as arguments to the Startup.Configure method. 有关详细信息,请参阅泛型主机限制启动构造函数注入 (aspnet/Announcements #353)For more information, see Generic Host restricts Startup constructor injection (aspnet/Announcements #353).

KestrelKestrel

  • 已更新 Kestrel 配置以迁移到泛型主机。Kestrel configuration has been updated for the migration to the Generic Host. 在 3.0 中,Kestrel 是在 ConfigureWebHostDefaults 提供的 Web 主机生成器上配置的。In 3.0, Kestrel is configured on the web host builder provided by ConfigureWebHostDefaults.
  • 已从 Kestrel 中删除连接适配器,并将其替换为连接中间件,这与 ASP.NET Core 管道中的 HTTP 中间件类似,但适用于较低级别的连接。Connection Adapters have been removed from Kestrel and replaced with Connection Middleware, which is similar to HTTP Middleware in the ASP.NET Core pipeline but for lower-level connections.
  • Kestrel 传输层已作为 Connections.Abstractions 中的公共接口公开。The Kestrel transport layer has been exposed as a public interface in Connections.Abstractions.
  • 通过将尾随标题移到新集合中,已解决了标头和尾部之间的歧义。Ambiguity between headers and trailers has been resolved by moving trailing headers to a new collection.
  • 线程不足会导致应用崩溃,而同步 I/O API(例如 HttpRequest.Body.Read)是导致线程不足的常见原因。Synchronous I/O APIs, such as HttpRequest.Body.Read, are a common source of thread starvation leading to app crashes. 在 3.0 中,默认情况下禁用 AllowSynchronousIOIn 3.0, AllowSynchronousIO is disabled by default.

有关详细信息,请参阅 从 ASP.NET Core 2.2 迁移到3。0For more information, see 从 ASP.NET Core 2.2 迁移到3。0.

默认情况下启用 HTTP/2HTTP/2 enabled by default

默认情况下,在 HTTPS 终结点的 Kestrel 中启用 HTTP/2。HTTP/2 is enabled by default in Kestrel for HTTPS endpoints. 当操作系统支持 HTTP/2 时,对 IIS 或 HTTP.sys 启用 HTTP/2 支持。HTTP/2 support for IIS or HTTP.sys is enabled when supported by the operating system.

根据请求提供事件计数器EventCounters on request

托管事件源 Microsoft.AspNetCore.Hosting 发出以下与传入请求有关的新 EventCounter 类型:The Hosting EventSource, Microsoft.AspNetCore.Hosting, emits the following new EventCounter types related to incoming requests:

  • requests-per-second
  • total-requests
  • current-requests
  • failed-requests

终结点路由Endpoint routing

增强了终结点路由,终结点路由可以让框架(例如 MVC)与中间件配合使用:Endpoint Routing, which allows frameworks (for example, MVC) to work well with middleware, is enhanced:

  • 中间件和终结点的顺序可在 Startup.Configure 的请求处理管道中进行配置。The order of middleware and endpoints is configurable in the request processing pipeline of Startup.Configure.
  • 终结点和中间件与其他基于 ASP.NET Core 的技术(如运行状况检查)很好地结合。Endpoints and middleware compose well with other ASP.NET Core-based technologies, such as Health Checks.
  • 终结点可以在中间件和 MVC 中实现策略,例如 CORS 或授权。Endpoints can implement a policy, such as CORS or authorization, in both middleware and MVC.
  • 可以将筛选器和属性置于控制器的方法中。Filters and attributes can be placed on methods in controllers.

有关详细信息,请参阅 ASP.NET Core 中的路由For more information, see ASP.NET Core 中的路由.

运行状况检查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.

有关详细信息,请参阅以下文章:For more information, see the following articles:

HttpContext 上的管道Pipes on HttpContext

现在可以使用 System.IO.Pipelines API 读取请求正文和写入响应正文。It's now possible to read the request body and write the response body using the System.IO.Pipelines API. 必须向The HttpRequest.BodyReader 属性提供可用于读取请求正文的 PipeReaderHttpRequest.BodyReader property provides a PipeReader that can be used to read the request body. 必须向The HttpResponse.BodyWriter 属性提供可用于写入响应正文的 PipeWriterHttpResponse.BodyWriter property provides a PipeWriter that can be used to write the response body. HttpRequest.BodyReaderHttpRequest.Body 流的模拟。HttpRequest.BodyReader is an analogue of the HttpRequest.Body stream. HttpResponse.BodyWriterHttpResponse.Body 流的模拟。HttpResponse.BodyWriter is an analogue of the HttpResponse.Body stream.

改进了 IIS 中的错误报告Improved error reporting in IIS

在 IIS 中托管 ASP.NET Core 应用时出现的启动错误现在会生成更丰富的诊断数据。Startup errors when hosting ASP.NET Core apps in IIS now produce richer diagnostic data. 如果适用,这些错误将报告给具有堆栈跟踪的 Windows 事件日志。These errors are reported to the Windows Event Log with stack traces wherever applicable. 此外,所有警告、错误和未经处理的异常都将记录到 Windows 事件日志中。In addition, all warnings, errors, and unhandled exceptions are logged to the Windows Event Log.

辅助角色服务和辅助角色 SDKWorker Service and Worker SDK

.NET Core 3.0 引入了新的辅助角色服务应用模板。.NET Core 3.0 introduces the new Worker Service app template. 可根据此模板开始在 .NET Core 中编写长期运行的服务。This template provides a starting point for writing long running services in .NET Core.

有关详情,请参阅:For more information, see:

转接标头中间件改进Forwarded Headers Middleware improvements

在以前版本的 ASP.NET Core 中,在部署到 Azure Linux 或除 IIS 以外的任何反向代理后,调用 UseHstsUseHttpsRedirection 会出现问题。In previous versions of ASP.NET Core, calling UseHsts and UseHttpsRedirection were problematic when deployed to an Azure Linux or behind any reverse proxy other than IIS. 转发 Linux 和非 IIS 反向代理的方案记录了以前版本的修复。The fix for previous versions is documented in Forward the scheme for Linux and non-IIS reverse proxies.

此方案已在 ASP.NET Core 3.0 中修复。This scenario is fixed in ASP.NET Core 3.0. 如果 ASPNETCORE_FORWARDEDHEADERS_ENABLED 环境变量设置为 true,则主机启用转接的标头中间件The host enables the Forwarded Headers Middleware when the ASPNETCORE_FORWARDEDHEADERS_ENABLED environment variable is set to true. 在容器映像中,ASPNETCORE_FORWARDEDHEADERS_ENABLED 设置为 trueASPNETCORE_FORWARDEDHEADERS_ENABLED is set to true in our container images.

性能改进Performance improvements

ASP.NET Core 3.0 包含了许多改进,可减少内存使用量并提高吞吐量:ASP.NET Core 3.0 includes many improvements that reduce memory usage and improve throughput:

  • 降低了使用内置的依赖项注入容器来实现作用域服务时的内存使用量。Reduction in memory usage when using the built-in dependency injection container for scoped services.
  • 减少跨框架的分配,包括中间件方案和路由。Reduction in allocations across the framework, including middleware scenarios and routing.
  • 降低了 WebSocket 连接的内存使用量。Reduction in memory usage for WebSocket connections.
  • 减少 HTTPS 连接的内存使用量并提高了其吞吐量。Memory reduction and throughput improvements for HTTPS connections.
  • 新的优化和完全异步 JSON 序列化程序。New optimized and fully asynchronous JSON serializer.
  • 减少了窗体分析的内存使用量并提高了其吞吐量。Reduction in memory usage and throughput improvements in form parsing.

ASP.NET Core 3.0 仅在 .NET Core 3.0 上运行ASP.NET Core 3.0 only runs on .NET Core 3.0

从 ASP.NET Core 3.0 开始,.NET Framework 不再是受支持的目标框架。As of ASP.NET Core 3.0, .NET Framework is no longer a supported target framework. 面向 .NET Framework 的项目可以使用 .NET Core 2.1 LTS 版本以完全受支持的方式继续。Projects targeting .NET Framework can continue in a fully supported fashion using the .NET Core 2.1 LTS release. 超过 .NET Core 2.1 的 3 年 LTS 期之后,将无限期地向大多数 ASP.NET Core 2.1.x 相关包提供支持。Most ASP.NET Core 2.1.x related packages will be supported indefinitely, beyond the three-year LTS period for .NET Core 2.1.

有关迁移信息,请参阅将代码从 .NET Framework 移植到 .NET CoreFor migration information, see Port your code from .NET Framework to .NET Core.

使用 ASP.NET Core 共享框架Use the ASP.NET Core shared framework

Microsoft.AspNetCore.App metapackage 中包含的 ASP.NET Core 3.0 共享框架不再需要项目文件中有一个显式 <PackageReference /> 元素。The ASP.NET Core 3.0 shared framework, contained in the Microsoft.AspNetCore.App metapackage, no longer requires an explicit <PackageReference /> element in the project file. 使用项目文件中的 Microsoft.NET.Sdk.Web SDK 时,会自动引用共享框架:The shared framework is automatically referenced when using the Microsoft.NET.Sdk.Web SDK in the project file:

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

从 ASP.NET Core 共享框架中删除的程序集Assemblies removed from the ASP.NET Core shared framework

从 ASP.NET Core 3.0 共享框架中删除的最值得注意的程序集有:The most notable assemblies removed from the ASP.NET Core 3.0 shared framework are:

有关从共享框架中删除的程序集的完整列表,请参阅从 Microsoft.AspNetCore.App 3.0 中删除的程序集For a complete list of assemblies removed from the shared framework, see Assemblies being removed from Microsoft.AspNetCore.App 3.0. 有关此更改的动机的详细信息,请参阅 3.0 中对 Microsoft.AspNetCore.App 所做的重大变更首先查看 ASP.NET Core 3.0 中的变更For more information on the motivation for this change, see Breaking changes to Microsoft.AspNetCore.App in 3.0 and A first look at changes coming in ASP.NET Core 3.0.