December 4, 2022

thec10

Super Technology

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


Microsoft’s ASP.Net Main 6, which has been readily available for creation use considering the fact that November 8, introduces a simplified hosting product that reduces the boilerplate code that you would usually need to generate to get your ASP.Internet Core application up and working. ASP.Net Main 6 would make a little bit less difficult to produce a new web application from scratch, in contrast with ASP.Net Main 5.

But what if you want to update an ASP.Web Main 5 undertaking to ASP.Internet Main 6? In that circumstance, you should be informed of the code you will require to write to migrate ASP.Web Main 5 code to ASP.Web Core 6. This short article provides several code samples that clearly show how you can do this.

To work with the code illustrations furnished in this short article, you need to have Visible Studio 2022 installed in your technique. If you do not presently have a duplicate, you can download Visible Studio 2022 right here.

Make an ASP.Web Main World wide web API job in Visual Studio 2022

Initial off, let’s build an ASP.Internet Main venture in Visual Studio 2022. Next these techniques will make a new ASP.Web Main Internet API 6 challenge in Visual Studio 2022:

  1. Start the Visual Studio 2022 IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.Net Core Website API” from the checklist of templates exhibited.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and locale for the new project.
  6. Optionally check out the “Place option and project in the identical directory” examine box, dependent on your tastes.
  7. Simply click Future.
  8. In the “Additional Information” window demonstrated following, make certain that the look at box that claims “Use controllers…” is checked, as we’ll be employing controllers instead of nominal APIs in this example. Go away the “Authentication Type” set to “None” (default).
  9. Make sure that the test packing containers “Enable Docker,” “Configure for HTTPS,” and “Enable Open API Support” are unchecked as we won’t be making use of any of those attributes here.
  10. Click on Make.

We’ll use this ASP.Internet Main 6 World wide web API task to illustrate migrations of ASP.Net Main 5 code to ASP.Net Core 6 in the subsequent sections of this write-up.

The Application course in ASP.Web Main 5

The following code snippet illustrates what a typical Application course appears like in ASP.Internet Core 5.

general public course Method

      community static void Main(string[] args)
            CreateHostBuilder(args).Establish().Run()
     
      general public static IHostBuilder CreateHostBuilder(string[] args)
            return Host.CreateDefaultBuilder(args).
            ConfigureWebHostDefaults(x => x.UseStartup ())
     

The Program course in ASP.Internet Core 6

With the introduction of the simplified hosting design in ASP.Net Main 6, you no lengthier have to use the Startup class. You can browse far more about this in my before posting listed here. Here’s how you would write a regular System course in ASP.Internet Main 6:

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

Add middleware in ASP.Web Main 5

The next code snippet displays how you can increase a middleware part in ASP.Internet Core 5. In our example, we’ll incorporate the reaction compression middleware.

general public class Startup

    general public void Configure(IApplicationBuilder application)
   
        app.UseResponseCompression()
   

Increase middleware in ASP.Net Main 6

To add a middleware part in ASP.Internet Core 6, you can use the pursuing code.

var builder = WebApplication.CreateBuilder(args)
var app = builder.Establish()
application.UseResponseCompression()
app.Operate()

Add routing in ASP.Web Main 5

To insert an endpoint in ASP.Net Core 5, you can use the adhering to code.

public course Startup

    public void Configure(IApplicationBuilder application)
   
        application.UseRouting()
        app.UseEndpoints(endpoints =>
       
            endpoints.MapGet("/check", () => "This is a test concept.")
        )
   

Increase routing in ASP.Web Core 6

You can increase an endpoint in ASP.Web Core 6 using the pursuing code.

var builder = WebApplication.CreateBuilder(args)
var app = builder.Build()
application.MapGet("/examination", () => "This is a take a look at concept.")
app.Operate()

Note that in ASP.Internet Core 6 you can insert endpoints to WebApplication without the need of getting to make express calls to the UseRouting or UseEndpoints extension solutions.

Incorporate companies in ASP.Net Main 5

The subsequent code snippet illustrates how you can add expert services to the container in ASP.Web Core 5.

community course Startup

    public void ConfigureServices(IServiceCollection solutions)
   
        // Incorporate constructed-in services
        companies.AddMemoryCache()
        services.AddRazorPages()
        solutions.AddControllersWithViews()
        // Incorporate a tailor made provider
        solutions.AddScoped()
   

Increase solutions in ASP.Web Main 6

To include services to the container in ASP.Web Main 6, you can use the pursuing code.

var builder = WebApplication.CreateBuilder(args)
// Insert crafted-in solutions
builder.Providers.AddMemoryCache()
builder.Solutions.AddRazorPages()
builder.Products and services.AddControllersWithViews()
// Increase a custom service
builder.Services.AddScoped()
var application = builder.Build()

Check an ASP.Web Core 5 or ASP.Web Main 6 software

You can test an ASP.Internet Core 5 application working with both TestServer or WebApplicationFactory. To check making use of TestServer in ASP.Net Main 5, you can use the adhering to code snippet.

[Fact]
general public async Task GetProductsTest()

    applying var host = Host.CreateDefaultBuilder()
        .ConfigureWebHostDefaults(builder =>
       
            builder.UseTestServer()
                    .UseStartup()
        )
        .ConfigureServices(services =>
       
            services.AddSingleton()
        )
        .Create()
    await host.StartAsync()
    var customer = host.GetTestClient()
    var reaction = await consumer.GetStringAsync("/getproducts")
    Assert.Equivalent(HttpStatusCode.Ok, reaction.StatusCode)

The adhering to code snippet shows how you can take a look at your ASP.Web Main 5 application utilizing WebApplicationFactory.

[Fact]
community async Job GetProductsTest()

    var software = new WebApplicationFactory()
        .WithWebHostBuilder(builder =>
       
            builder.ConfigureServices(providers =>
           
                services.AddSingleton()
            )
        )
    var consumer = software.CreateClient()
    var response = await shopper.GetStringAsync("/getproducts")
    Assert.Equal(HttpStatusCode.Okay, reaction.StatusCode)

You can use the identical code to test employing TestServer or WebApplicationFactory in .Net 5 and .Web 6. 

Increase a logging company in ASP.Web Main 5

Logging vendors in ASP.Web Main are made use of to keep logs. The default logging companies involved in ASP.Net Main are the Debug, Console, EventLog, and EventSource logging suppliers.

You can use the ClearProviders system to very clear all logging vendors and add a specific logging provider or your possess personalized logging supplier. The next code snippet illustrates how you can take away all ILoggerProvider instances and incorporate the Console logging supplier in ASP.Web Main 5.

community static IHostBuilder CreateHostBuilder(string[] args) =>
   Host.CreateDefaultBuilder(args)
      .ConfigureLogging(logging =>
         logging.ClearProviders()
         logging.AddConsole()
      )
      .ConfigureWebHostDefaults(webBuilder =>
         webBuilder.UseStartup()
      )

Insert a logging supplier in ASP.Internet Main 6

In ASP.Net Core 6, when you get in touch with WebApplication.CreateBuilder, it provides the Console, Debug, EventLog, and EventSource logging suppliers. The adhering to code snippet demonstrates how you can very clear the default logging suppliers and add only the Console logging service provider in ASP.Net Core 6.

var builder = WebApplication.CreateBuilder(args)
//Obvious default logging companies
builder.Logging.ClearProviders()
//Code to insert expert services to the container
builder.Logging.AddConsole()
var application = builder.Make()

The code examples provided listed here illustrate the distinctive means we incorporate middleware, routing, solutions, and logging vendors in ASP.Web Main 5 and in ASP.Web Core 6, as effectively as differences in the Method class and screening. These snippets should enable you when operating with ASP.Web Main 6 purposes, and get you off to a superior start off when you migrate your ASP.Internet Core 5 programs to ASP.Net Core 6.

Copyright © 2022 IDG Communications, Inc.



Source link