26 February, 2024 New York

Posts

How you can migrate ASP.NET Core 5 code to ASP.NET Core 6

Microsoft’s ASP.NET Core 6, which has been to be had for manufacturing use since November 8, introduces a simplified internet hosting style that reduces the boilerplate code that you’d in a different way wish to write to get your ASP.NET Core utility up and operating. ASP.NET Core 6 makes somewhat more uncomplicated to create a brand new internet utility from scratch, when compared with ASP.NET Core 5.

However what if you wish to replace an ASP.NET Core 5 mission to ASP.NET Core 6? If so, you must pay attention to the code it is very important write emigrate ASP.NET Core 5 code to ASP.NET Core 6. This text items a number of code samples that display how you’ll be able to do that.

To paintings with the code examples equipped on this article, you’ll have Visible Studio 2022 put in on your device. When you don’t have already got a duplicate, you’ll be able to obtain Visible Studio 2022 right here.

Create an ASP.NET Core Internet API mission in Visible Studio 2022

First off, let’s create an ASP.NET Core mission in Visible Studio 2022. Following those steps will create a brand new ASP.NET Core Internet API 6 mission in Visible Studio 2022:

  1. Release the Visible Studio 2022 IDE.
  2. Click on on “Create new mission.”
  3. Within the “Create new mission” window, make a choice “ASP.NET Core Internet API” from the listing of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new mission” window, specify the title and site for the brand new mission.
  6. Optionally test the “Position resolution and mission in the similar listing” test field, relying in your personal tastes.
  7. Click on Subsequent.
  8. Within the “Further Data” window proven subsequent, make sure that the test field that claims “Use controllers…” is checked, as we’ll be the usage of controllers as a substitute of minimum APIs on this instance. Depart the “Authentication Sort” set to “None” (default).
  9. Make sure that the test bins “Allow Docker,” “Configure for HTTPS,” and “Allow Open API Beef up” are unchecked as we received’t be the usage of any of the ones options right here.
  10. Click on Create.

We’ll use this ASP.NET Core 6 Internet API mission for example migrations of ASP.NET Core 5 code to ASP.NET Core 6 within the next sections of this newsletter.

The Program magnificence in ASP.NET Core 5

The next code snippet illustrates what a standard Program magnificence looks as if in ASP.NET Core 5.

public magnificence Program
{
      public static void Major(string[] args) {
            CreateHostBuilder(args).Construct().Run();
      }
      public static IHostBuilder CreateHostBuilder(string[] args) {
            go back Host.CreateDefaultBuilder(args).
            ConfigureWebHostDefaults(x => x.UseStartup <Startup> ());
      }
}

The Program magnificence in ASP.NET Core 6

With the advent of the simplified internet hosting style in ASP.NET Core 6, you not have to make use of the Startup magnificence. You’ll learn extra about this in my previous article right here. Right here’s how you can write a standard Program magnificence in ASP.NET Core 6:

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

Upload middleware in ASP.NET Core 5

The next code snippet displays how you’ll be able to upload a middleware part in ASP.NET Core 5. In our instance, we’ll upload the reaction compression middleware.

public magnificence Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseResponseCompression();
    }
}

Upload middleware in ASP.NET Core 6

So as to add a middleware part in ASP.NET Core 6, you’ll be able to use the next code.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Construct();
app.UseResponseCompression();
app.Run();

Upload routing in ASP.NET Core 5

So as to add an endpoint in ASP.NET Core 5, you’ll be able to use the next code.

public magnificence Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapGet("/check", () => "It is a check message.");
        });
    }
}

Upload routing in ASP.NET Core 6

You’ll upload an endpoint in ASP.NET Core 6 the usage of the next code.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Construct();
app.MapGet("/check", () => "It is a check message.");
app.Run();

Notice that during ASP.NET Core 6 you’ll be able to upload endpoints to WebApplication with no need to make specific calls to the UseRouting or UseEndpoints extension strategies.

Upload products and services in ASP.NET Core 5

The next code snippet illustrates how you’ll be able to upload products and services to the container in ASP.NET Core 5.

public magnificence Startup
{
    public void ConfigureServices(IServiceCollection products and services)
    {
        // Upload integrated products and services
        products and services.AddMemoryCache();
        products and services.AddRazorPages();
        products and services.AddControllersWithViews();
        // Upload a customized carrier
        products and services.AddScoped<IProductRepository, ProductRepository>();
    }
}

Upload products and services in ASP.NET Core 6

So as to add products and services to the container in ASP.NET Core 6, you’ll be able to use the next code.

var builder = WebApplication.CreateBuilder(args);
// Upload integrated products and services
builder.Services and products.AddMemoryCache();
builder.Services and products.AddRazorPages();
builder.Services and products.AddControllersWithViews();
// Upload a customized carrier
builder.Services and products.AddScoped<IProductRepository, ProductRepository>();
var app = builder.Construct();

Check an ASP.NET Core 5 or ASP.NET Core 6 utility

You’ll check an ASP.NET Core 5 utility the usage of both TestServer or WebApplicationFactory. To check the usage of TestServer in ASP.NET Core 5, you’ll be able to use the next code snippet.

[Fact]
public async Process GetProductsTest()
{
    the usage of var host = Host.CreateDefaultBuilder()
        .ConfigureWebHostDefaults(builder =>
        {
            builder.UseTestServer()
                    .UseStartup<WebApplication1.Startup>();
        })
        .ConfigureServices(products and services =>
        {
            products and services.AddSingleton<IProductService, MockProductService>();
        })
        .Construct();
    wait for host.StartAsync();
    var consumer = host.GetTestClient();
    var reaction = wait for consumer.GetStringAsync("/getproducts");
    Assert.Equivalent(HttpStatusCode.OK, reaction.StatusCode);
}

The next code snippet displays how you’ll be able to check your ASP.NET Core 5 utility the usage of WebApplicationFactory.

[Fact]
public async Process GetProductsTest()
{
    var utility = new WebApplicationFactory<Program>()
        .WithWebHostBuilder(builder =>
        {
            builder.ConfigureServices(products and services =>
            {
                products and services.AddSingleton<IProductService, MockProductService>();
            });
        });
    var consumer = utility.CreateClient();
    var reaction = wait for consumer.GetStringAsync("/getproducts");
    Assert.Equivalent(HttpStatusCode.OK, reaction.StatusCode);
}

You’ll use the similar code to check the usage of TestServer or WebApplicationFactory in .NET 5 and .NET 6. 

Upload a logging supplier in ASP.NET Core 5

Logging suppliers in ASP.NET Core are used to retailer logs. The default logging suppliers integrated in ASP.NET Core are the Debug, Console, EventLog, and EventSource logging suppliers.

You’ll use the ClearProviders solution to transparent all logging suppliers and upload a selected logging supplier or your individual customized logging supplier. The next code snippet illustrates how you’ll be able to take away all ILoggerProvider circumstances and upload the Console logging supplier 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>();
      });

Upload a logging supplier in ASP.NET Core 6

In ASP.NET Core 6, whilst you name WebApplication.CreateBuilder, it provides the Console, Debug, EventLog, and EventSource logging suppliers. The next code snippet displays how you’ll be able to transparent the default logging suppliers and upload simplest the Console logging supplier in ASP.NET Core 6.

var builder = WebApplication.CreateBuilder(args);
//Transparent default logging suppliers
builder.Logging.ClearProviders();
//Code so as to add products and services to the container
builder.Logging.AddConsole();
var app = builder.Construct();

The code examples equipped right here illustrate the other ways we upload middleware, routing, products and services, and logging suppliers in ASP.NET Core 5 and in ASP.NET Core 6, in addition to variations within the Program magnificence and trying out. Those snippets must mean you can when operating with ASP.NET Core 6 programs, and get you off to a just right get started whilst you migrate your ASP.NET Core 5 programs to ASP.NET Core 6.

Copyright © 2022 IDG Communications, Inc.

Supply By means of https://www.infoworld.com/article/3665659/how-to-migrate-aspnet-core-5-code-to-aspnet-core-6.html