Use Minimal Hosting to Migrate ASP.NET Core 3.1 Projects to the latest in ASP.NET 6.0
Table of Contents
Background
In my previous post on migrating your ASP.NET Core 3.1 application to ASP.NET 6.0 , I have briefly mentioned about the new minimal hosting model, that unifies the Startup and Program classes into a single Program class in Program.cs file. I also mentioned the choice of sticking to the earlier way of using Startup and the Generic host by the ASP.NET Core 3.1 templates which is fully supported in the ASP.NET 6.0 or using the new minimal hosting model. In that post I showed the migration to 6.0 along with running the migrated version using the earlier model.
In this post, I shall use the minimal hosting model for the migration. So we shall continue with the same solution named WebAPICoreMVCClient from where we left earlier with Visual Studio 2022 Community version.
YouTube Version
The YouTube version of this blog is available here
New minimal hosting model
The new .NET 6 minimal hosting model for ASP.NET Core apps requires only one file and a few lines of code. Apps migrating to 6.0 don’t need to use the new minimal hosting model.
The following code from the ASP.NET Core empty template creates an app using the new minimal hosting model:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
The minimal hosting model:
- Significantly reduces the number of files and lines of code required to create an app. Only one file is needed with four lines of code.
- Unifies
Startup.csandProgram.csinto a singleProgram.csfile. - Uses top-level statements to minimize the code required for an app.
- Uses global
usingdirectives to eliminate or minimize the number ofusingstatement lines required.
Minimal Hosting Model for the Web API project
Now let’s switch over to Visual Studio 2022 solution that we started here . In our Solution, our Web API Startup.cs and Program.cs files (after removing the unused usings are shown as below):
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using WebAPI.Models;
namespace APIControllers
{
public class Startup
{
IConfiguration Configuration;
public Startup(IConfiguration configuration)
{
// Init Serilog configuration
Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ICustomerRepository, CustomerRepository>();
services.AddSingleton<IOrderRepository, OrderRepository>();
services.AddCors();
/*services.AddControllersWithViews().AddNewtonsoftJson();*/
services.AddControllersWithViews()
.AddNewtonsoftJson()
.AddXmlDataContractSerializerFormatters();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
loggerFactory.AddSerilog();
app.UseCors(builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace APIControllers
{
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<Startup>();
});
}
}
On inspection of the Startup.cs file we see that we have configured a third party Serilog package for logging and have used CORS (Cross Origin Resource Sharing) with an associated NuGet package. In ASP.NET Core 6, the preceding code (of both the classes) is replaced by the following code in the Program class (Program.cs file).
var builder = WebApplication.CreateBuilder(args);
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.File("C:\\Temp\\log.txt", rollingInterval: RollingInterval.Minute)
.CreateLogger();
// Add services to the container.
builder.Services.AddSingleton<ICustomerRepository, CustomerRepository>();
builder.Services.AddSingleton<IOrderRepository, OrderRepository>();
builder.Services.AddCors();
builder.Services.AddControllersWithViews()
.AddNewtonsoftJson()
.AddXmlDataContractSerializerFormatters();
builder.Host.UseSerilog(Log.Logger, dispose: true);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseCors(builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
app.UseStaticFiles();
app.UseRouting();
app.Run();
On inspecting the Program class above, we find that a new WebApplication is used at the top to create a WebApplicationBuilder object. Also the ConfigureServices and Configure methods of the Startup class have been done away with. Instead, the services property of the WebApplicationBuilder type calls the various extension methods directly and adds them to the collection of services, which was carried out by the ConfigureServices method in the Startup class earlier :
builder.Services.AddCors();
The Configure method of the Startup class that was implementing the middleware pipeline is now achieved by building the WebApplicationBuilder to create a WebApplication object (app). This app object then configures the middleware pipeline by calling the relevant extension methods like below:
app.UseStaticFiles();
app.UseRouting();
Here I have created the Serilog package to write to a file in my C:\\Temp directory by initialising the logger in the Program.cs file directly (in contrast to writing the path in the appsettings.json file and then referencing it in the Startup class). I had to do it as I could not find a way of injecting a configuration object as dependency in the minimal hosting model.
Preparation Leading to Minimal Hosting Program class
I had to do a few things before I could write my Program.cs file to look like a neat way using the Minimal Hosting model. These are :
- Use of Top-level statement
- Use of Global Using statements
ASP.NET 6.0 allows only one top level statement in a project. So what is this Top-Level statement thingy?
Starting in C# 9, you don’t have to explicitly include a Main method in a console application project. Instead, you can use the top-level statements feature to minimize the code you have to write. In this case, the compiler generates a class and Main method entry point for the application. A project can have any number of additional source code files that don’t have top-level statements. It is important to note (so once again : An application must have only one entry point. A project can have only one file with top-level statements.)
To use the new C# 10 feature of Global Using statements, I created a GlobalUsing.cs file in the Web API project and added all the using statements used by the classes in the project, thereby taking away the need of writing using statements individually in all the classes (unlike what we are used to do so far!)
My GlobalUsing.cs file looks like this:
global using Microsoft.AspNetCore.Hosting; global using Microsoft.Extensions.Hosting; global using Microsoft.AspNetCore.Builder; global using Microsoft.Extensions.Configuration; global using Microsoft.Extensions.DependencyInjection; global using Microsoft.Extensions.Logging; global using Serilog; global using WebAPI.Models;
In future, if I were to extend my project with more classes, all I will need to do is to add any other Using statements (as may be required), within the GlobalUsing.cs file so as not to clutter the individual class files.
I am yet not complete as I shall like to (although remember it is not a must, and is just a choice to be consistent) to implement the minimal hosting for the MVC (WebAPIConsume) project.
Minimal Hosting Model for the MVC project
Let’s switch over to focus on the WebAPIConsume (MVC) project in the Visual Studio 2022.
The Startup and Program class code is presented below (before implementing the minimal hosting model):
Startup class:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Text;
using WebAPIConsume.Models;
namespace APIConsume
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Start}/{action=Index}/{id?}");
});
}
}
}
Program class:
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace APIConsume
{
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<Startup>();
});
}
}
After implementing the global using and top level statement like earlier we did for the Web API project, the program class for the MVC (WebAPIConsume) project looks like below
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (builder.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Start}/{action=Index}/{id?}");
});
app.Run();
The explanation of this unified Program class is similar to the explanation for the Web API project, so I shall leave that.
Run the solution
Now I will run the application by clicking the Start (Green) arrow on top which renders these projects on the browsers in the same way as we have seen in this post
Conclusion
In this post, I have shown how we can migrate from ASP.NET Core 3.1 to ASP.NET 6.0 using the minimal hosting model introduced in the latter. The minimal hosting model uses WebApplication builder (instead of Generic Host) and combines the Startup and Program classes into a single Program class. We have further seen how the code for the Program class is further trimmed by implementing Global Using and top-level statements.
Follow Me Here