Categories
Uncategorized

[Translation] ASP.NET Core 3.0’s new features

table of Contents

  • ASP.NET Core 3.0 的新增功能
    • Blazor
      • Blazor Server
      • Blazor WebAssembly (Preview)

        Razor components

    • gRPC
    • SignalR

        The new JSON serialization

    • The new Razor instructions

      Certificates and Kerberos authentication

      Change template

    • 通用主机

        Host Configuration

        Startup constructor injection changes

    • Kestrel
    • Enabled by default HTTP / 2

      Request counter

      Endpoint Routing

      Health Check

      Pipeline on HttpContext

      IIS, improved error reporting

      Services role services and supporting roles SDK

      Improved Forwarded header middleware

      Performance improvements

      ASP.NET Core 3.0 can run only on the .NET Core 3.0

      Use ASP.NET Core sharing framework

      Removed from ASP.NET Core shared framework assemblies

ASP.NET Core 3.0’s new features

Full text translated from the English version of Microsoft’s official documentation What’s new in ASP.NET Core 3.0

This article focuses on the ASP.NET Core 3.0 is the most important change, and provides connectivity-related documents.

Blazor

Blazor is a new framework ASP.NET Core, .NET for building interactive use of client Web UI:

    Using C # instead of JavaScript to create rich, interactive UI.

    Sharing written in .NET server-side and client-side application logic.

    UI will render as HTML and CSS, to provide support for a wide range of browsers, including mobile browsers.

Blazor framework supports scenarios:

    Reusable UI components (Razor component)

    Client routes

    Component layout

    Support for dependency injection

    Form and Verification

    Use Razor libraries to build a component library

    JavaScript interoperability

For more information, see: Blazor Introduction to ASP.NET Core of.

Blazor Server

Blazor the component rendering logic logic and UI updates were decoupled. Blazor Server support on the server application hosted in ASP.NET Core Razor components. SignalR update the UI by a connection process. Blazor Server is supported in ASP.NET Core 3.0 in.

Blazor WebAssembly (Preview)

Blazor based applications can also be used to run directly in the browser WebAssembly .NET runtime. Blazor WebAssembly in the preview state in ASP.NET Core 3.0, and is not supported. Future versions will support ASP.NET Core Blazor WebAssembly.

Razor components

Blazor applications are constructed from components (Components) formed. Assembly is self-contained user interface elements, such as a page, dialog box, or the like form. .NET component is a normal class, used to define the presentation logic and UI client-side event handlers. You can create rich interactive Web applications without JavaScript.

Blazor The components are typically written using Razor syntax, HTML and C # it is natural fusion. Razor assembly Razor Pages (page) and MVC view (view) similar because they both use Razor. And – based pages and view “request-response” different model, UI components designed for use with the synthesis.

gRPC

gRPC:

    It is a popular high performance RPC (Remote Procedure Call) framework.

    It provides a “contract-first” approach to API development.

  • 使用各种现代的技术,例如:

      HTTP / 2 transmitted through

      Using Protocol Buffers as an interface description language

      Binary serialization format

  • 提供以下功能:

      Authentication

      Bidirectional data flow and control flow

      Cancellation and Timeout

gRPC function ASP.NET Core 3.0 include:

    Grpc.AspNetCore – a framework for ASP.NET Core gRPC bearer services. gRPC on ASP.NET Core capable of logging, Dependency injection (DI) authentication and authorization standard ASP.NET Core functions integrated.

    Grpc.Net.Client – oriented .NET Core, constructed gRPC client on the HttpClient.

    Grpc.Net.ClientFactory – gRPC client for integration with HttpClientFactory.

Introduction to ASP.NET Core on the gRPC: For more information, see

SignalR

See Updating Signal code to get migration instructions. SignalR System.Text.Json now to serialize / deserialize JSON message. For reduction is described based on a sequence of program Newtonsoft.Json, see the switch to Newtonsoft.Json.

In SignalR JavaScript and .NET client, added support for automatic reconnection. By default, the client tries to automatically reconnect, and after 2, 10 and 30 seconds (if necessary) to try again. If the client successfully reconnected, it will receive a new connection ID. Automatic reconnection is selectively added to:

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

Reconnection interval may be specified by transferring a duration-based array ms:

.withAutomaticReconnect([0, 3000, 5000, 10000, 15000, 30000])
//.withAutomaticReconnect([0, 2000, 10000, 30000]) 默认时间间隔

You can pass a custom implementation for full control reconnect interval.

If the reconnection fails to reconnect after the last interval, then:

    The client considers the connection is offline.

    The client stops trying to reconnect.

In order to provide UI feedback when the connection is broken, SignalR Client API has been extended to include the following event handler:

    onreconnecting: it provides the opportunity to disable UI or inform the user that the application is offline for developers.

    onreconnected: Reconnecting enables developers the opportunity to update the UI.

The following code uses onreconnecting update the UI when 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;
});

The following code uses onreconnected update the UI when the connection is restored:

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

When the hub method requires authorization, SignalR 3.0 and later provide a custom resource authorization handler. The resource is an instance of HubInvocationContext. HubInvocationContext include:

  • HubCallerContext
  • Name hub method is called.

    Method of parameter hub.

Application Examples The following considerations chat room, which allows multiple tissue application log in Azure Active Directory. Anyone with Microsoft accounts can log chat, but only members of your organization can disable user or view the user chats. The application may restrict certain features specific user.

public class DomainRestrictedRequirement :
    AuthorizationHandler,
    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(
                "[email protected]",
                StringComparison.OrdinalIgnoreCase);
        }

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

In the foregoing code, DomainRestrictedRequirement as a custom IAuthorizationRequirement. Since the transfer of HubInvocationContext resources, the internal logic can be:

    Check that you are calling the context hub.

    Decide whether to allow the user to perform a specific hub approach.

Each hub can be modified method uses the policy name, the code will be checked at runtime. When a client attempts to call each hub method, DomainRestrictedRequirement handler will run and control access to the method. DomainRestrictedRequirement-based approach to control access:

    All logged-in users can call SendMessage method.

    Only sign in with an email address @ jabbr.net users can view the history of the user.

    Only [email protected] can prevent users enter 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)
    {
    }
}

Creating DomainRestricted strategy might involve:

    Adding a new policy in Startup.cs in.

    The demand from DomainRestrictedRequirement defined as a parameter.

    Middleware license registration DomainRestricted.

services
    .AddAuthorization(options =>
    {
        options.AddPolicy("DomainRestricted", policy =>
        {
            policy.Requirements.Add(new DomainRestrictedRequirement());
        });
    });

SignalR hub using endpoint routing. SignalR hub connection explicitly done previously:

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

In previous versions, developers need to enable the controller, Razor pages and SignalR hub at various locations. Explicit connection leads to a series of nearly identical fragments route:

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

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

SignalR 3.0 hub can be routed through the routing endpoint. Use endpoint routing, you can configure all the usual routes in UseRouting in:

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

ASP.NET Core 3.0 SignalR Added:

Client to the streaming server. By the streaming client to the server, the server-side method may Example IAsyncEnumerable or ChannelReader employed. In the following examples C #, UploadStream method on the hub string stream received from the client:

public async Task UploadStream(IAsyncEnumerable stream)
{
    await foreach (var item in stream)
    {
        // 处理流中的内容
    }
}

.NET client application, or it may be a IAsyncEnumerable example ChannelReader stream is passed as a parameter of the method UploadStream hub.

After circulating for completion, and exit the local function, the stream completion of sending (After the for loop has completed and the local function exits, the stream completion is sent):

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

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

JavaScript client application stream parameters SignalR Subject (or a RxJS Subject) UploadStream hub used in the above method.

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

When captured JavaScript code string and ready to send it to the server, it may use a method to process subject.next string.

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

The first two use a similar snippet of code, you can create real-time streaming experience.

The new JSON serialization

Now by default, ASP.NET Core 3.0 System.Text.Json use JSON serialization:

    Asynchronous reading and writing JSON.

    Optimized for UTF-8 text.

    It will typically have a higher performance than Newtonsoft.Json.

To add to ASP.NET Core 3.0 Json.NET see Adding JSON-based format support Newtonsoft.Json of.

The new Razor instructions

The following list contains the new Razor instructions:

    @attribute - @attribute instruction given attributes to the generated class or the page view. For example: @attribute [Authorize].

    @implements - @implements command generated class implements an interface. For example: @implements IDisposable.

Certificates and Kerberos authentication

Certificate authentication requirements:

    Configure the server to receive the certificate.

    Add authentication middleware Startup.Configure in.

    Add a certificate authentication service in Startup.ConfigureServices in.

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(
        CertificateAuthenticationDefaults.AuthenticationScheme)
            .AddCertificate();
    // 其他服务配置已移除。
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseAuthentication();
    // 其他应用配置已移除。
}

Certificate authentication options (Options) provides the following features:

    Accept the self-signed certificate.

    Check certificate revocation.

    Check whether the certificate provided by the right to use the logo.

Body default user (user principal) is constructed in accordance with the attribute certificate. The body contains a user event. By event phase should be supplemented or replaced by the body. For more information, see Configuring Certificate Authentication in ASP.NET Core in.

Windows authentication has been extended to the Linux and macOS. In previous versions, Windows authentication is limited to IIS and HttpSys. In ASP.NET Core 3.0 in, Kestrel can on Windows, Linux and macOS to join a Windows domain hosts use Negotiate (negotiation), Kerberos and NTLM. Kestrel verification support infrastructure for these identities provided by Microsoft.AspNetCore.Authentication.Negotiate NuGet package. As with other authentication service, configure authentication by using the program within the range, and then configure the service:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
        .AddNegotiate();
    // 其他服务配置已移除。
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseAuthentication();
    // 其他应用配置已移除。
}

Host Requirements:

    Windows host must service principal name (SPN) added to the user account that hosts the application.

  • Linux 和 macOS 主机必须加入域。

      SPN process must be created for the Web.

      Tables must be generated and key configuration file on the host.

For more information, see Configuring Windows Authentication in ASP.NET Core in.

Change template

Web UI template (Razor Pages, MVC controllers and with a view) was deleted following:

    "Cookie consent" UI no longer included. To enable "Cookie consent" function in the application ASP.NET Core 3.0 template generated, please refer to the general data protection legislation (GDPR) ASP.NET Core of support.

    Now, the script and the associated static assets as a local file reference instead of using a CDN. For more information, see the script and the associated static assets are now cited as a local file instead of using a CDN (aspnet / AspNetCore.Docs # 14350).

Angular template has been updated to use Angular 8.

By default, Razor Library (RCL) is the default template for Razor component development. New template in Visual Studio templates provide options and support for page views. At the command line to create a template from RCL, please pass -support-pages-and-views option (dotnet new razorclasslib -support-pages-and-views).

Universal Host

ASP.NET Core 3.0 .NET generic host template. Previous versions used WebHostBuilder. Use .NET Core Universal Host (HostBuilder), the ASP.NET Core can be better integrated with other application-specific and non-Web-server scheme. For more information, see HostBuilder replace WebHostBuilder.

Host Configuration

Before publishing ASP.NET Core 3.0, environment variables prefixed with ASPNETCORE_ will be loaded, the host for the Web host configuration. In 3.0, AddEvironmentVariables for loading with the previous environment variables DOTNET_ chase, using CreateDefaultBuilder for host configuration.

Startup constructor injection changes

Generic Host support only what type of Startup constructor injection:

  • IHostEnvironment
  • IWebHostEnvironment
  • IConfiguration

All services will still be in the form of direct injection Startup.Configure method parameters, see generic host restriction Startup constructor injection (aspnet / Announcements # 353).

Kestrel

    In order to migrate to a generic host, Kestrel configuration has been updated. In 3.0, Kestrel builder (host builder) is configured on the Web hosting ConfigureWebHostDefaults provided.

    The connection adapter (Connection Adapter) Kestrel deleted from, replaced by intermediate connection (Connection Middleware). Middleware The middleware similar to HTTP ASP.NET Core pipe, but for a lower level connection.

    Kestrel transport layers have been disclosed in a public interface of Connections.Abstractions.

    Ambiguity between the header (header) and tail (Trailer) has passed the tail header (trailing header) to a new set of solution.

    Synchronous IO API (eg HttpRequest.Body.Read) is a common cause thread starvation in turn causes the program to crash. In 3.0, AllowSynchronousIO is disabled by default.

For more information, see Kestrel - migration from ASP.NET Core 2.2 Dao 3.0.

Enabled by default HTTP / 2

By default, Kestrel enabled HTTP / 2 for the HTTPS endpoint. When the operating system support, support for IIS or HTTP.sys of HTTP / 2 will be enabled.

Request counter

Hosting EventSource (Microsoft.AspNetCore.Hosting) issued the following EventCounter associated with the incoming request:

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

Endpoint Routing

Routing endpoint has been enhanced, so that the route frameworks (e.g., MVC) can work better together with middleware:

    Middleware sequence and endpoints can be configured in Startup.Configure request processing pipeline.

    Endpoints and middleware good choreography with other ASP.NET Core-based technologies (such as health checks).

    Endpoints can implement various strategies in middleware and MVC, such as CORS or authorization.

    And a filter characteristic (attribute) can be placed on the method in the controller.

For more information, see the route in ASP.NET Core.

Health Check

Health check by using a common routing endpoint host. In Startup.Configure using endpoint URL or relative path is constructed in the call MapHealthChecks endpoints:

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

Health checks endpoints can:

    Specifying one or more allowed host / port.

    Require authorization.

    Requirements CORS.

For more information, please see the following articles:

    Health Check - migration from ASP.NET Core 2.2 Dao 3.0

    Health Check in ASP.NET Core

Pipeline on HttpContext

You can now use System.IO.Pipelines API requests to read and write text response body. HttpRequest.BodyReader property provides a PipeReader, may be used to read the body of the request; HttpResponse.BodyWriter property provides a PipeWriter, can be used to write the response body. HttpRequest.BodyReader similar composition HttpRequest.Body stream; HttpResponse.BodyWriter HttpResponse.Body stream was similar.

IIS, improved error reporting

Now, start hosting ASP.NET Core application in IIS error will generate a richer diagnostic data. These errors will use the stack trace where applicable, reporting to the Windows event log. In addition, all of the warnings, errors and unhandled exceptions are logged to the Windows event log.

Services role services and supporting roles SDK

.NET Core 3.0 introduces a new helper role services (Worker Service) application template. The template is a long-running services written in .NET Core the starting point.

For more information, see:

    .NET Core role as an auxiliary service that runs Windows (.NET Core Workers as Windows Services)

    Using managed service implementation in a background task in ASP.NET Core

    Bearing in Windows ASP.NET Core Services

Improved Forwarded header middleware

In earlier versions of ASP.NET Core, the application after deployment to Azure Linux or any reverse proxy other than IIS, call the UseHsts and UseHttpsRedirection is problematic. Linux and non-IIS forwarding reverse proxy scenario describes a previous version of restoration.

This scene has been fixed in ASP.NET Core 3.0 in. When ASPNETCORE_FORWARDEDHEADERS_ENABLED environment variable is set to true, the panel will enable Forwarded header middleware. In the container of the mirror ASP.NET Core, ASPNETCORE_FORWARDEDHEADERS_ENABLED has been set to true.

Performance improvements

ASP.NET Core 3.0 includes many improvements that can reduce memory usage and improve throughput:

    When the built-in dependency injection container for scoped service, reduce the amount of memory.

    Reducing the overall memory allocation framework, including various types of middleware and routing scenarios.

    Reducing memory usage WebSocket connection.

    HTTPS connection to reduce memory usage and improve throughput.

    The new, optimized, fully asynchronous JSON serializer.

    Reducing memory usage resolved forms (form), and increase throughput.

ASP.NET Core 3.0 can run only on the .NET Core 3.0

Starting ASP.NET Core 3.0, .NET Framework is not an objective framework supported. With projects that target .NET Framework can continue to run in a fully supported status by using the .NET Core 2.1 LTS version. The vast majority of packages associated with the ASP.NET Core 2.1.x, will receive support during long-term support in .NET Core 2.1 three years. (Most ASP.NET Core 2.1.x related packages will be supported indefinitely, beyond the 3 year LTS period for .NET Core 2.1.)

For more information about migration, see porting code from .NET Framework to .NET Core.

Use ASP.NET Core sharing framework

ASP.NET Core 3.0 sharing framework (shared framework) Microsoft.AspNetCore.App element included in the package is no longer needed in the project file explicit element. When using Microsoft.NET.Sdk.Web SDK in the project file is automatically shared reference framework:

Removed from ASP.NET Core shared framework assemblies

Most notably, the assembly is removed from the centralized sharing program is ASP.NET Core 3.0:

    Newtonsoft.Json (Json.NET). To Json.NET added to the ASP.NET Core 3.0, see Adding JSON format supports Newtonsoft.Json of. ASP.NET Core 3.0 introduces System.Text.Json to read and write JSON. For more information, please refer to the documentation in the new JSON serialization.

  • Entity Framework Core

A complete list of the assembly about sharing in the framework removal, please refer to the assembly removed from Microsoft.AspNetCore.App 3.0 in. About an incentive to this modification, for more information please refer to the Preliminary Change Microsoft.AspNetCore.App breaking changes in 3.0 and ASP.NET Core 3.0 in.

Leave a Reply