How to use the minimal hosting model in ASP.NET Core 6

The minimal hosting model in ASP.NET Core 6 means having to write less boilerplate code to get your application up and running.

How to use the minimal hosting model in ASP.NET Core 6
Thinkstock

ASP.NET Core 6 has introduced a new hosting model that is much more simplified and streamlined, reducing the amount of boilerplate code you need to write to get your ASP.NET Core application up and running. This article introduces this new hosting model with relevant code examples wherever appropriate.

To work with the code examples provided in this article, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here.

Create an ASP.NET Core Web API project in Visual Studio 2022

First off, let’s create an ASP.NET Core project in Visual Studio 2022. Following these steps will create a new ASP.NET Core Web API 6 project:

  1. Launch the Visual Studio 2022 IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web API” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
  7. Click Next.
  8. In the “Additional Information” window shown next, select .NET 6.0 as the target framework from the drop-down list at the top. Leave the “Authentication Type” as “None” (default).
  9. Ensure that the check boxes “Enable Docker,” “Configure for HTTPS,” and “Enable Open API Support” are unchecked as we won’t be using any of those features here.
  10. Click Create.

We’ll use this ASP.NET Core 6 Web API project to work with the minimal hosting model in the subsequent sections of this article.

Program class in ASP.NET Core 6

When you create a new ASP.NET Core 6 project in Visual Studio, the Program class would look like this:

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseAuthorization();
app.MapControllers();
app.Run();

We’ll use this class in the subsequent sections of this article.

Configure middleware in ASP.NET Core 6

Middleware components in the ASP.NET Core 6 request pipeline are used to customize the way requests and responses are handled. You can use middleware to inspect, route, or modify the request and response messages that flow through the pipeline.

We can see how middleware configuration has been streamlined in ASP.NET Core 6 in comparison with ASP.NET Core 5. The following code snippet can be used to add static file serving (i.e., HTML, CSS, image, and JavaScript files) to the request processing pipeline in ASP.NET Core 5:

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseStaticFiles();
    }
  //Other members
}

This configuration has been reduced to two lines in ASP.NET Core 6. You can write the following code to add the same middleware to the request processing pipeline in ASP.NET Core 6:

// Configure the HTTP request pipeline.
var app = builder.Build();
app.UseStaticFiles();

Configure routing in ASP.NET Core 6

Now let’s compare routing configuration in ASP.NET Core 5 and ASP.NET Core 6. You can use the following piece of code to create an endpoint in an ASP.NET Core 5 application:

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapGet("/", () =>
            "This is an endpoint created in ASP.NET 5");
        });
    }
}

You can achieve the same in ASP.NET Core 6 with much less code:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "This is an endpoint created in ASP.NET 6");
app.Run();

Add a logging provider in ASP.NET Core 6

Logging providers are classes that implement the ILoggingProvider interface. Logging providers store the logs in a log target that has been configured in the application. The exception is the console logging provider, which displays the logs as standard output. ASP.NET Core includes the following built-in logging providers:

  • Console
  • Debug
  • EventSource
  • EventLog

You can use the following code snippet to add console logging to your ASP.NET Core 5 application:

public static IHostBuilder CreateHostBuilder(string[] args) = >
Host.CreateDefaultBuilder(args).ConfigureLogging(loggingBuilder = > {
      loggingBuilder.ClearProviders();
      loggingBuilder.AddConsole();
}).ConfigureWebHostDefaults(webBuilder = >{
      webBuilder.UseStartup < Startup > ();
});

Here again ASP.NET Core 6 is less verbose. You can add console logging using three lines of code in ASP.NET Core 6:

var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Logging.AddConsole();

Add services in ASP.NET Core 6

The syntax for adding services has changed in ASP.NET Core 6, but it’s not any terser. You can add services to the built-in dependency injection container in ASP.NET Core 5 using the following code:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMemoryCache();
    services.AddScoped<IProductRepository, ProductRepository>();
}

You can achieve the same in ASP.NET Core 6 using this code:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMemoryCache();
builder.Services.AddScoped<IProductRepository, ProductRepository>();
var app = builder.Build();

Add a configuration provider in ASP.NET Core 6

Configuration providers are used to read and write configuration data from various pre-configured configuration data sources. ASP.NET Core 5 provides excellent support for working with configuration data stored in JSON files, environment variables, XML files, INI Files, command-line arguments, etc. You can use the following code to add a configuration provider in ASP.NET Core 5:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration(config =>
        {
            config.AddIniFile("appsettings.ini");
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

And you can achieve the same in ASP.NET Core 6 in just three lines:

var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddIniFile("appsettings.ini");
var app = builder.Build();

The new hosting paradigm in ASP.NET Core 6 is simplified, requiring less boilerplate code to get your simple ASP.NET Core application up and running. To maintain backward compatibility, you can still use the Startup class in ASP.NET Core 6.

Copyright © 2021 IDG Communications, Inc.

How to choose a low-code development platform