Microsoft’s ASP.NET Core 6, which has been available for production use since November 8, introduces a simplified hosting model that reduces the boilerplate code that you would otherwise need to write to get your ASP.NET Core application up and running. ASP.NET Core 6 makes a bit easier to create a new web application from scratch, compared with ASP.NET Core 5.
But what if you want to update an ASP.NET Core 5 project to ASP.NET Core 6? In that case, you should be aware of the code you will need to write to migrate ASP.NET Core 5 code to ASP.NET Core 6. This article presents several code samples that show how you can do this.
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 in Visual Studio 2022:
- Launch the Visual Studio 2022 IDE.
- Click on “Create new project.”
- In the “Create new project” window, select “ASP.NET Core Web API” from the list of templates displayed.
- Click Next.
- In the “Configure your new project” window, specify the name and location for the new project.
- Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
- Click Next.
- In the “Additional Information” window shown next, ensure that the check box that says “Use controllers…” is checked, as we’ll be using controllers instead of minimal APIs in this example. Leave the “Authentication Type” set to “None” (default).
- 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.
- Click Create.
We’ll use this ASP.NET Core 6 Web API project to illustrate migrations of ASP.NET Core 5 code to ASP.NET Core 6 in the subsequent sections of this article.
The Program class in ASP.NET Core 5
The following code snippet illustrates what a typical Program class looks like in ASP.NET Core 5.
public class Program
{
public static void Main(string[] args) {
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) {
return Host.CreateDefaultBuilder(args).
ConfigureWebHostDefaults(x => x.UseStartup <Startup> ());
}
}
The Program class in ASP.NET Core 6
With the introduction of the simplified hosting model in ASP.NET Core 6, you no longer have to use the Startup class. You can read more about this in my earlier article here. Here’s how you would write a typical Program class in ASP.NET Core 6:
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();
Add middleware in ASP.NET Core 5
The following code snippet shows how you can add a middleware component in ASP.NET Core 5. In our example, we’ll add the response compression middleware.
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseResponseCompression();
}
}
Add middleware in ASP.NET Core 6
To add a middleware component in ASP.NET Core 6, you can use the following code.
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseResponseCompression();
app.Run();
Add routing in ASP.NET Core 5
To add an endpoint in ASP.NET Core 5, you can use the following code.
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/test", () => "This is a test message.");
});
}
}
Add routing in ASP.NET Core 6
You can add an endpoint in ASP.NET Core 6 using the following code.
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/test", () => "This is a test message.");
app.Run();
Note that in ASP.NET Core 6 you can add endpoints to WebApplication without having to make explicit calls to the UseRouting or UseEndpoints extension methods.
Add services in ASP.NET Core 5
The following code snippet illustrates how you can add services to the container in ASP.NET Core 5.
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Add built-in services
services.AddMemoryCache();
services.AddRazorPages();
services.AddControllersWithViews();
// Add a custom service
services.AddScoped<IProductRepository, ProductRepository>();
}
}
Add services in ASP.NET Core 6
To add services to the container in ASP.NET Core 6, you can use the following code.
var builder = WebApplication.CreateBuilder(args);
// Add built-in services
builder.Services.AddMemoryCache();
builder.Services.AddRazorPages();
builder.Services.AddControllersWithViews();
// Add a custom service
builder.Services.AddScoped<IProductRepository, ProductRepository>();
var app = builder.Build();
Test an ASP.NET Core 5 or ASP.NET Core 6 application
You can test an ASP.NET Core 5 application using either TestServer or WebApplicationFactory. To test using TestServer in ASP.NET Core 5, you can use the following code snippet.
[Fact]
public async Task GetProductsTest()
{
using var host = Host.CreateDefaultBuilder()
.ConfigureWebHostDefaults(builder =>
{
builder.UseTestServer()
.UseStartup<WebApplication1.Startup>();
})
.ConfigureServices(services =>
{
services.AddSingleton<IProductService, MockProductService>();
})
.Build();
await host.StartAsync();
var client = host.GetTestClient();
var response = await client.GetStringAsync("/getproducts");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
The following code snippet shows how you can test your ASP.NET Core 5 application using WebApplicationFactory.
[Fact]
public async Task GetProductsTest()
{
var application = new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
{
builder.ConfigureServices(services =>
{
services.AddSingleton<IProductService, MockProductService>();
});
});
var client = application.CreateClient();
var response = await client.GetStringAsync("/getproducts");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
You can use the same code to test using TestServer or WebApplicationFactory in .NET 5 and .NET 6.
Add a logging provider in ASP.NET Core 5
Logging providers in ASP.NET Core are used to store logs. The default logging providers included in ASP.NET Core are the Debug, Console, EventLog, and EventSource logging providers.
You can use the ClearProviders method to clear all logging providers and add a specific logging provider or your own custom logging provider. The following code snippet illustrates how you can remove all ILoggerProvider instances and add the Console logging provider in ASP.NET Core 5.
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>{
logging.ClearProviders();
logging.AddConsole();
})
.ConfigureWebHostDefaults(webBuilder =>{
webBuilder.UseStartup<Startup>();
});
Add a logging provider in ASP.NET Core 6
In ASP.NET Core 6, when you call WebApplication.CreateBuilder, it adds the Console, Debug, EventLog, and EventSource logging providers. The following code snippet shows how you can clear the default logging providers and add only the Console logging provider in ASP.NET Core 6.
var builder = WebApplication.CreateBuilder(args);
//Clear default logging providers
builder.Logging.ClearProviders();
//Code to add services to the container
builder.Logging.AddConsole();
var app = builder.Build();
The code examples provided here illustrate the different ways we add middleware, routing, services, and logging providers in ASP.NET Core 5 and in ASP.NET Core 6, as well as differences in the Program class and testing. These snippets should help you when working with ASP.NET Core 6 applications, and get you off to a good start when you migrate your ASP.NET Core 5 applications to ASP.NET Core 6.
Copyright © 2022 IDG Communications, Inc.
Discussion about this post