Thursday, July 7, 2022
HomeITHow one can migrate ASP.NET Core 5 code to ASP.NET Core 6

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


Microsoft’s ASP.NET Core 6, which has been accessible for manufacturing use since November 8, introduces a simplified internet hosting mannequin that reduces the boilerplate code that you’d in any other case want to put in writing to get your ASP.NET Core software up and working. ASP.NET Core 6 makes a bit simpler to create a brand new net software from scratch, in contrast with ASP.NET Core 5.

However what if you wish to replace an ASP.NET Core 5 challenge to ASP.NET Core 6? In that case, you need to be conscious of the code you’ll need to put in writing emigrate ASP.NET Core 5 code to ASP.NET Core 6. This text presents a number of code samples that present how you are able to do this.

To work with the code examples supplied on this article, you need to have Visible Studio 2022 put in in your system. If you happen to don’t have already got a duplicate, you possibly can obtain Visible Studio 2022 right here.

Create an ASP.NET Core Net API challenge in Visible Studio 2022

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

  1. Launch the Visible Studio 2022 IDE.
  2. Click on on “Create new challenge.”
  3. Within the “Create new challenge” window, choose “ASP.NET Core Net API” from the listing of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new challenge” window, specify the title and placement for the brand new challenge.
  6. Optionally test the “Place answer and challenge in the identical listing” test field, relying in your preferences.
  7. Click on Subsequent.
  8. Within the “Further Data” window proven subsequent, be certain that the test field that claims “Use controllers…” is checked, as we’ll be utilizing controllers as a substitute of minimal APIs on this instance. Go away the “Authentication Kind” set to “None” (default).
  9. Make sure that the test packing containers “Allow Docker,” “Configure for HTTPS,” and “Allow Open API Assist” are unchecked as we received’t be utilizing any of these options right here.
  10. Click on Create.

We’ll use this ASP.NET Core 6 Net API challenge for example migrations of ASP.NET Core 5 code to ASP.NET Core 6 within the subsequent sections of this text.

The Program class in ASP.NET Core 5

The next code snippet illustrates what a typical Program class appears like in ASP.NET Core 5.

public class Program
{
      public static void Important(string[] args) {
            CreateHostBuilder(args).Construct().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 internet hosting mannequin in ASP.NET Core 6, you not have to make use of the Startup class. You may learn extra about this in my earlier article right here. Right here’s how you’ll write a typical Program class in ASP.NET Core 6:

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

Add middleware in ASP.NET Core 5

The next code snippet exhibits how one can add a middleware element in ASP.NET Core 5. In our instance, we’ll add the response compression middleware.

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

Add middleware in ASP.NET Core 6

So as to add a middleware element in ASP.NET Core 6, you should use the next code.

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

Add routing in ASP.NET Core 5

So as to add an endpoint in ASP.NET Core 5, you should use the next code.

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

Add routing in ASP.NET Core 6

You may add an endpoint in ASP.NET Core 6 utilizing the next code.

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

Be aware that in ASP.NET Core 6 you possibly can add endpoints to WebApplication with out having to make specific calls to the UseRouting or UseEndpoints extension strategies.

Add providers in ASP.NET Core 5

The next code snippet illustrates how one can add providers to the container in ASP.NET Core 5.

public class Startup
{
    public void ConfigureServices(IServiceCollection providers)
    {
        // Add built-in providers
        providers.AddMemoryCache();
        providers.AddRazorPages();
        providers.AddControllersWithViews();
        // Add a customized service
        providers.AddScoped<IProductRepository, ProductRepository>();
    }
}

Add providers in ASP.NET Core 6

So as to add providers to the container in ASP.NET Core 6, you should use the next code.

var builder = WebApplication.CreateBuilder(args);
// Add built-in providers
builder.Companies.AddMemoryCache();
builder.Companies.AddRazorPages();
builder.Companies.AddControllersWithViews();
// Add a customized service
builder.Companies.AddScoped<IProductRepository, ProductRepository>();
var app = builder.Construct();

Take a look at an ASP.NET Core 5 or ASP.NET Core 6 software

You may check an ASP.NET Core 5 software utilizing both TestServer or WebApplicationFactory. To check utilizing TestServer in ASP.NET Core 5, you should use the next code snippet.

[Fact]
public async Activity GetProductsTest()
{
    utilizing var host = Host.CreateDefaultBuilder()
        .ConfigureWebHostDefaults(builder =>
        {
            builder.UseTestServer()
                    .UseStartup<WebApplication1.Startup>();
        })
        .ConfigureServices(providers =>
        {
            providers.AddSingleton<IProductService, MockProductService>();
        })
        .Construct();
    await host.StartAsync();
    var consumer = host.GetTestClient();
    var response = await consumer.GetStringAsync("/getproducts");
    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}

The next code snippet exhibits how one can check your ASP.NET Core 5 software utilizing WebApplicationFactory.

[Fact]
public async Activity GetProductsTest()
{
    var software = new WebApplicationFactory<Program>()
        .WithWebHostBuilder(builder =>
        {
            builder.ConfigureServices(providers =>
            {
                providers.AddSingleton<IProductService, MockProductService>();
            });
        });
    var consumer = software.CreateClient();
    var response = await consumer.GetStringAsync("/getproducts");
    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}

You should utilize the identical code to check utilizing TestServer or WebApplicationFactory in .NET 5 and .NET 6. 

Add a logging supplier in ASP.NET Core 5

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

You should utilize the ClearProviders methodology to clear all logging suppliers and add a selected logging supplier or your individual customized logging supplier. The next code snippet illustrates how one can take away all ILoggerProvider situations and add 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>();
      });

Add a logging supplier in ASP.NET Core 6

In ASP.NET Core 6, whenever you name WebApplication.CreateBuilder, it provides the Console, Debug, EventLog, and EventSource logging suppliers. The next code snippet exhibits how one can clear the default logging suppliers and add solely the Console logging supplier in ASP.NET Core 6.

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

The code examples supplied right here illustrate the alternative ways we add middleware, routing, providers, and logging suppliers in ASP.NET Core 5 and in ASP.NET Core 6, in addition to variations within the Program class and testing. These snippets ought to enable you when working with ASP.NET Core 6 purposes, and get you off to an excellent begin whenever you migrate your ASP.NET Core 5 purposes to ASP.NET Core 6.

Copyright © 2022 IDG Communications, Inc.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments