New features of ASP.NET Core 5.0

In this article, we review the most important changes in ASP.NET Core 5.0

Improved ASP.NET Core MVC and Razor  

Model binding DateTime as UTC

Model binding supports binding of UTC time strings to DateTime. If the request contains a UTC time string, the binding model binds it to the UTC DateTime.

Model binding and validation with C# 9 record types

C # 9 record types can be used with the binding model in the MVC controller or Razor Page. Record types are a good way to record data models that are transmitted over the network. For example, PersonController uses Person record type with binding model and form validation:


  1. public record Person([Required] string Name, [Range(0, 150)] int Age);  
  2.   
  3. public class PersonController  
  4. {  
  5.    public IActionResult Index() => View();  
  6.   
  7.    [HttpPost]  
  8.    public IActionResult Index(Person person)  
  9.    {  
  10.           // ...  
  11.    }  
  12. }  

Person / Index.cshtml file:


  1. @model Person  
  2.   
  3. Name: <input asp-for="Model.Name" />  
  4. <span asp-validation-for="Model.Name" />  
  5.   
  6. Age: <input asp-for="Model.Age" />  
  7. <span asp-validation-for="Model.Age" />  

Improved DynamicRouteValueTransformer

DynamicRouteValueTransformer introduced ASP.NET Core 3.1 as a way to use custom endpoints to dynamically select MVC controller action or Razor page. ASP.NET Core 5.0 applications can send status to DynamicRouteValueTransformer and filter the set of selected endpoints.

Web API

OpenAPI Specification Default

OpenAPI Specification is an industry standard for describing HTTP APIs and integrating them into complex business processes or third-party applications. OpenAPI is widely supported by all cloud providers and many APIs. Applications that publish OpenAPI documentation from web APIs have a variety of new opportunities that can be used with these APIs. Partner with Swashbuckle.AspNetCore open source project maintainers The ASP.NET Core API template includes NuGet dependencies on Swashbuckle. Swashbuckle is a popular NuGet open source package that dynamically distributes OpenAPI documentation. Swashbuckle does this by viewing API controllers and generating an OpenAPI document at runtime, or at build time using the Swashbuckle CLI.

In ASP.NET Core 5.0, web API templates enable OpenAPI support by default. To disable OpenAPI:

Command line:

  1. dotnet new webapi --no-openapi true  

From Visual Studio: Uncheck Enable OpenAPI support

All csproj files. Created for web API projects include references to the Swashbuckle.AspNetCore NuGet package.


  1. <ItemGroup>  
  2.     <PackageReference Include="Swashbuckle.AspNetCore" Version="5.5.1" />  
  3. </ItemGroup>  

The generated code of the template contains the code in Startup.ConfigureServices that enables the production of the OpenAPI document:


  1. public void ConfigureServices(IServiceCollection services)  
  2. {  
  3.   
  4.     services.AddControllers();  
  5.     services.AddSwaggerGen(c =>  
  6.     {  
  7.         c.SwaggerDoc("v1"new OpenApiInfo { Title = "WebApp1", Version = "v1" });  
  8.     });  
  9. }  


The Swashbuckle middleware method adds Startup.Configure, which enables the following:  

1. Document production process  

2. Default Swagger UI screen in development mode

The generated code of the template does not explicitly display the API description when it is published for production.


  1. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  2. {  
  3.     if (env.IsDevelopment())  
  4.     {  
  5.         app.UseDeveloperExceptionPage();  
  6.         app.UseSwagger();  
  7.         app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json""WebApp1 v1"));  
  8.     }  
  9.   
  10.     app.UseHttpsRedirection();  
  11.   
  12.     app.UseRouting();  
  13.   
  14.     app.UseAuthorization();  
  15.   
  16.     app.UseEndpoints(endpoints =>  
  17.     {  
  18.         endpoints.MapControllers();  
  19.     });  
  20. }  

Import Azure API Management

When OpenAPI projects enable the ASP.NET Core API, Visual Studio 2019 version 16.8 and later versions automatically provide an additional step in the release process. Developers using Azure API Management have the opportunity to automatically import APIs into Azure API Management during its publishing stream:


Better startup experience for web API projects

With OpenAPI enabled by default, the application startup experience (F5) is significantly improved for web API developers. With ASP.NET Core 5.0, the web API template is pre-configured to load the Swagger UI page. The Swagger UI page provides both documentation added to the published API, and allows testing APIs with a single click.


Blazor

Performance improvements

For NET 5. With a particular focus on sophisticated UI rendering and JSON serialization, significant improvements have been made to Blazor WebAssembly runtime performance. In performance tests, Blazor WebAssembly in NET 5. is two to three times faster for most scenarios.

CSS Isolation

Blazor now supports the definition of CSS styles that are restricted to a specific component. Component-specific CSS styles make it easy to reason about styles in the program and prevent unwanted side effects from global styles.

New InputFile component

The InputFile component allows you to read one or more files selected by the user for upload.

Component virtualization

Understanding component rendering performance is enhanced by using Blazor framework internal virtualization support.

Ontoggle event support

Blazor events now support the ontoggle DOM event.

Set UI focus in Blazor applications

Use the FocusAsync method on elements to set the UI focus on elements.

Custom Attributes Validations

Custom validation classes are useful when integrated with CSS frameworks such as Bootstrap.

IAsyncDisposable support

Blazor components now support the IAsyncDisposable interface for asynchronous distribution of allocated resources.

Isolation of JavaScript

Blazor enables JavaScript separation in standard JavaScript modules.

Form components support display name

The following internal components support displays with the DisplayName parameter:

InputDate

InputNumber

InputSelect

gRPC

Many performance improvements have been made in gRPC.

SignalR

SignalR Hub filters

SignalR Hub filters, called Hub pipelines in ASP.NET SignalR, are features that allow code to run before and after called Hub methods. Executing code before and after the Hub methods being called is similar to the way middleware can execute code before and after an HTTP request. Common uses include logging, error handling, and argument validation.

SignalR parallel hub call

ASP.NET Core SignalR is now able to manage parallel hub calls. The default behavior can be changed to allow clients to call more than one hub method at a time:


  1. public void ConfigureServices(IServiceCollection services)  
  2. {  
  3.     services.AddSignalR(options =>  
  4.     {  
  5.         options.MaximumParallelInvocationsPerClient = 5;  
  6.     });  
  7. }  

Add Messagepack support to SignalR Java client

A new package, com.microsoft.signalr.messagepack, has added MessagePack support for the SignalR Java client. To use withHubProtocol (new MessagePackHubProtocol ()), MessagePack hub protocol. Add to connection builder:


  1. HubConnection hubConnection = HubConnectionBuilder.create(  
  2.                            "http://localhost:53353/MyHub")  
  3.                .withHubProtocol(new MessagePackHubProtocol())  
  4.                .build();  

Kestrel

Configurable endpoints: Kestrel can detect configuration changes sent to KestrelServerOptions.Configure and drop them from existing endpoints and connect them to new endpoints without the need to restart the program when the parameter is true, reloadOnChange. By default when using ConfigureWebHostDefaults or CreateDefaultBuilder, Kestrel closes under the "Kestrel" configuration section by enabling reloadOnChange. Applications must send reloadOnChange: true when KestrelServerOptions.Configure is called manually to receive reloadable endpoints.

Improved HTTP / 2 response headers.

Support for other endpoint types in socket transfers: Added to the new API introduced in System.Net.Sockets, Kestrel socket transfers allow you to connect to existing file management and Unix domain sockets. Support for connection to existing file management allows you to use existing Systemd integration without the need for libuv transport.

Special endpoint options for Kestrel via configuration

Support for configuration Endpoint-specific options for Kestrel have been added via configuration. The configuration of these endpoints includes the following:

HTTP protocols used  

TLS protocols used  

Certificate selected

Client certificate mode

Config allows you to specify which certificate is selected based on the specified server name. The server name is part of the Server Name Indication (SNI) extension to the TLS protocol represented by the client.

The following example shows how to specify endpoint options using the configuration file:


  1. {  
  2.   "Kestrel": {  
  3.     "Endpoints": {  
  4.       "EndpointName": {  
  5.         "Url""https://*",  
  6.         "Sni": {  
  7.           "a.example.org": {  
  8.             "Protocols""Http1AndHttp2",  
  9.             "SslProtocols": [ "Tls11""Tls12"],  
  10.             "Certificate": {  
  11.               "Path""testCert.pfx",  
  12.               "Password""testPassword"  
  13.             },  
  14.             "ClientCertificateMode" : "NoCertificate"  
  15.           },  
  16.           "*.example.org": {  
  17.             "Certificate": {  
  18.               "Path""testCert2.pfx",  
  19.               "Password""testPassword"  
  20.             }  
  21.           },  
  22.           "*": {  
  23.             // At least one sub-property needs to exist per  
  24.             // SNI section or it cannot be discovered via  
  25.             // IConfiguration  
  26.             "Protocols""Http1",  
  27.           }  
  28.         }  
  29.       }  
  30.     }  
  31.   }  
  32. }  

Server Name Indication (SNI) is a TLS extension that includes a virtual domain as part of SSL negotiation. This means that the virtual domain name, or hostname, can be used to identify the end point of the network.

Containers

Prior to .NET 5.0, building and releasing Dockerfile for ASP.NET Core applications required capturing the entire .NET Core SDK. And has an ASP.NET Core image. With this release, the capture bytes of SDK images are reduced and the bytes captured for the ASP.NET Core image are largely removed.

Azure Active Directory authentication با Microsoft.Identity.Web

ASP.NET Core project templates are now integrated with Microsoft.Identity.Web to manage authentication with Azure Activity Directory (Azure AD). The Microsoft.Identity.Web package provides the following:

Better experience for authentication through Azure AD

An easier way for users to access Azure resources, including Microsoft Graph.  

Allow anonymous access to an endpoint

The AllowAnonymous method extension allows anonymous access to the endpoint:


  1. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  2. {  
  3.     app.UseRouting();  
  4.   
  5.     app.UseAuthentication();  
  6.     app.UseAuthorization();  
  7.   
  8.     app.UseEndpoints(endpoints =>  
  9.     {  
  10.         endpoints.MapGet("/", async context =>  
  11.         {  
  12.             await context.Response.WriteAsync("Hello World!");  
  13.         })  
  14.         .AllowAnonymous();  
  15.     });  
  16. }  

JSON Console Logger

In addition to supporting custom formatters, we can also add a built-in JSON formatter that publishes custom JSON logs for the console. The following code shows how to switch from the default logger to JSON:


  1. public static IHostBuilder CreateHostBuilder(string[] args) =>  
  2.            Host.CreateDefaultBuilder(args)  
  3.   .ConfigureLogging(logging =>  
  4.   {  
  5.      logging.AddJsonConsole(options =>  
  6.      {  
  7.          options.JsonWriterOptions = new JsonWriterOptions()  
  8.          { Indented = true };  
  9.      });  
  10.   })  
  11.   .ConfigureWebHostDefaults(webBuilder =>  
  12.   {  
  13.     webBuilder.UseStartup<Startup>();  
  14.   });  

The log messages released for the console are in JSON format:


  1. {  
  2.   "EventId": 0,  
  3.   "LogLevel""Information",  
  4.   "Category""Microsoft.Hosting.Lifetime",  
  5.   "Message""Now listening on: https://localhost:5001",  
  6.   "State": {  
  7.     "Message""Now listening on: https://localhost:5001",  
  8.     "address""https://localhost:5001",  
  9.     "{OriginalFormat}""Now listening on: {address}"  
  10.   }  
  11. }  

Conclusion

In this article, we tried to review some of the most important features added to ASP.NET Core 5.0. ASP.NET Core 5.0 In addition to the above, other good and new changes such as auto-refresh with dotnet watch, Startup class activation control, JSON method extension for HttpRequest and HttpResponse, application of attribute [Compare] on properties in Razor model Page and other items.



User:sinahabibi
1/19/2021
Visit:47
Asp.Net

Release of ASP.NET Core 5 Top Features of ASP.NET Core 5 Benefits of Working with ASP.NET Core 5 Latest Changes in ASP.NET Core 5 Changes in ASP.NET Core 5 Migration to ASP.NET Core 5
You must be logged in to post a comment