the-best-new-features-in-asp.net-core-6

The best new features in ASP.NET Core 6

Learn the most important new features and enhancements in ASP.NET Core 6, a major upgrade to Microsoft’s framework for building modern web applications.




The best new features in ASP.NET Core 6

Clem Onojeghuo / Koto Feja / Getty Images

Microsoft .NET 6 arrived in November 2021 with all kinds of great new features for .NET developers. The biggest highlight of .NET 6, though, is ASP.NET Core 6, a major upgrade of Microsoft’s open source framework for building modern web applications.

ASP.NET Core 6 is built on top of the .NET Core runtime and allows you to build and run applications on Windows, Linux, and macOS. ASP.NET Core 6 combines the features of Web API and MVC. This article discusses what’s new in ASP.NET 6, with some code examples.

To work with the code examples provided in this article, you should have Visual Studio 2022 installed in your computer. You can download Visual Studio 2022 here.

Now let’s dive into the new features in ASP.NET Core 6.

Hot Reload

Hot Reload is one of the most striking new features added in .NET 6. You can take advantage of this feature to modify the user interface when your ASP.NET Core 6 application is in execution. You can see the changes reflected once you save them — you don’t need to rebuild and restart the application. This feature boosts developer productivity considerably.

Minimal APIs

ASP.NET Core 6 lets you build lightweight services (also called minimal APIs) that don’t require a template or controller class. In addition, you can use the extension methods of the IEndpointConventionBuilder interface to build lightweight services that have no template or controller. You can create lightweight services or APIs in the Startup class or the Program class.

You can take advantage of some of the extension methods of the IEndpointConventionBuilder interface to map requests. Here is the list of these extension methods:

  • MapControllers
  • MapGet
  • MapPut
  • MapPost
  • MapDelete
  • MapRazorPages
  • MapGrpcService
  • MapHub

The MapGet, MapPut, MapPost, and MapDelete methods are used to connect the request delegate to the routing system. The MapControllers method is used for controllers, MapRazorPages for Razor Pages, MapHub for SignalR, and MapGrpcService for gRPC.

For an example, the following code snippet illustrates how you can use a lightweight service to write a “Hello World” response in the Program.cs file.

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.MapGet("https://www.infoworld.com/", (Func)(() => "Hello World!"));

Merger of the Program and Startup classes

In ASP.NET Core 5 and earlier, we have had to work with two classes to build and configure the application. These classes are the Program and Startup classes, which are located in the Program.cs and Startup.cs files.

Here is an example of a typical Startup class in ASP.NET Core 5:

public class Startup

    {

        public Startup(IConfiguration configuration)

        {

            Configuration = configuration;

        }

         public IConfiguration Configuration { get; }

         public void ConfigureServices(IServiceCollection services)

        {

            services.AddControllers();

            services.AddSingleton();

        }

        public void Configure(IApplicationBuilder app,

        IWebHostEnvironment env)

        {

             if (env.IsDevelopment())

            {

                app.UseDeveloperExceptionPage();

            }

            else

            {

                app.UseExceptionHandler("https://www.infoworld.com/Home/Error");

                app.UseHsts();

            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>

            {

                endpoints.MapControllerRoute(

                    name: "default",

                    pattern: "{controller=Home}/{action=Index}/{id?}");

            });

        }

    }

With ASP.NET 6, the Program and Startup classes have been merged into the Program class. Here is an example of the Program class in ASP.NET Core 6:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

builder.Services.AddSingleton();

var app = builder.Build();

if (app.Environment.IsDevelopment())

{

    app.UseDeveloperExceptionPage();

}

else

{

    app.UseExceptionHandler("https://www.infoworld.com/Home/Error");

    app.UseHsts();

}

app.UseHttpsRedirection();

app.UseRouting();

app.UseAuthorization();

app.MapControllers();

app.Run();

Program.cs file changes

The new console template dramatically simplifies the code you need to write for a program. The console template no longer contains a Program class. In essence, you only need to write the Main method now.

In previous .NET versions, when you created a new ASP.NET Core project, a class named Program would be created automatically inside a file named Program.cs. The Program class would include the Main method, which is where the execution of an ASP.NET Core application starts. Main is the method where a web application is built, configured, and executed.

When you create a new console application project in .NET 6, Visual Studio creates a default Program.cs file that contains this code:

// See https://aka.ms/new-console-template for more information

Console.WriteLine("Hello, World!");

When you create a new console application project in .NET 5, the default Program.cs file contains this code:

using System;

namespace IDGNet6Demo

{

    internal class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("Hello World!");

        }

    }

}

In ASP.NET Core 5 and earlier, the typical Program.cs file will contain this code:

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 ();

      });

}

And in ASP.NET Core 6, the typical Program.cs file will contain this code:

using NET6Demo;

Host.CreateDefaultBuilder(args)

    .ConfigureWebHostDefaults(webBuilder =>

    {

        webBuilder.UseStartup();

    }).Build().Run();

Note that you will no longer find a Startup.cs file by default in ASP.NET Core 6. However, if you want backward compatibility with earlier versions of ASP.NET Core, or you’re simply more comfortable with the old style, you can create a Startup class in the project manually.

Then call the UseStartup method to specify the Startup class as shown in the preceding code snippet.

HTTP Logging middleware

Support for the HTTP Logging middleware has been introduced in ASP.NET Core 6. You can take advantage of this middleware in ASP.NET Core 6 to log information about HTTP requests and responses that include one or more of the following:

  • Request information
  • Response information
  • Request and response headers
  • Body of the request
  • Properties

Blazor improvements

There are several improvements in Blazor in ASP.NET Core 6. Some of the most important include:

  • Ability to render components from JavaScript.
  • Support for preserving prerendered state.
  • Support for custom event args.
  • Support for JavaScript initializers.
  • Ability to render components dynamically using the DynamicComponent class.
  • Ability to define error boundaries using the ErrorBoundary class.

Improved support for IAsyncDisposable

You also have enhanced support for IAsyncDisposable on your controllers, classes, page models, and view components to release async resources.

Failure to dispose of an asynchronous disposable resource may result in deadlocks. The IAsyncDisposable interface solves this problem by freeing up resources asynchronously. The IAsyncDisposable interface is a part of the System namespace that was introduced in C# 8.0.

Just as you implement the Dispose() method of the IDisposable interface for synchronous calls, you should implement the DisposeAsync() method of the IAsyncDisposable interface to perform clean-up operations and release resources asynchronously.

The .NET 6 ecosystem provides a simplified development model, improved performance, and enhanced productivity. Many enhancements have been introduced in ASP.NET Core 6 to improve application performance and reduce allocations. By the same token, developers benefit from many improvements that make developing performant, modern web apps both faster and easier.

Joydip Kanjilal is a Microsoft MVP in ASP.Net, as well as a speaker and author of several books and articles. He has more than 20 years of experience in IT including more than 16 years in Microsoft .Net and related technologies.

Copyright © 2022 IDG Communications, Inc.