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

[ad_1]

Microsoft’s ASP.Web Main 6, which has been available for output use considering that November 8, introduces a simplified web hosting design that cuts down the boilerplate code that you would usually want to produce to get your ASP.Web Main application up and working. ASP.Web Core 6 makes a bit easier to create a new net software from scratch, when compared with ASP.Web Core 5.

But what if you want to update an ASP.Internet Core 5 project to ASP.Internet Main 6? In that situation, you ought to be knowledgeable of the code you will need to have to compose to migrate ASP.Net Core 5 code to ASP.Net Core 6. This report offers many code samples that exhibit how you can do this.

To function with the code examples furnished in this report, you ought to have Visible Studio 2022 put in in your program. If you don’t now have a duplicate, you can obtain Visual Studio 2022 here.

Produce an ASP.Net Main World wide web API challenge in Visual Studio 2022

Initially off, let us make an ASP.Web Core task in Visible Studio 2022. Pursuing these measures will produce a new ASP.Internet Core Net API 6 job in Visible Studio 2022:

  1. Start the Visual Studio 2022 IDE.
  2. Click on on “Create new challenge.”
  3. In the “Create new project” window, pick out “ASP.Web Core Web API” from the listing of templates shown.
  4. Simply click Next.
  5. In the “Configure your new project” window, specify the title and spot for the new project.
  6. Optionally examine the “Place resolution and challenge in the same directory” test box, relying on your preferences.
  7. Click Following.
  8. In the “Additional Information” window demonstrated following, guarantee that the check box that claims “Use controllers…” is checked, as we’ll be making use of controllers in its place of minimal APIs in this illustration. Depart the “Authentication Type” set to “None” (default).
  9. Be certain that the examine containers “Enable Docker,” “Configure for HTTPS,” and “Enable Open up API Support” are unchecked as we will not be applying any of these features right here.
  10. Click Build.

We’ll use this ASP.Web Main 6 Web API venture to illustrate migrations of ASP.Net Core 5 code to ASP.Internet Core 6 in the subsequent sections of this posting.

The Plan class in ASP.Net Main 5

The adhering to code snippet illustrates what a normal Method course looks like in ASP.Net Main 5.

public course Software

      public static void Main(string[] args)
            CreateHostBuilder(args).Make().Operate()
     
      public static IHostBuilder CreateHostBuilder(string[] args)
            return Host.CreateDefaultBuilder(args).
            ConfigureWebHostDefaults(x => x.UseStartup ())
     

The Program course in ASP.Web Core 6

With the introduction of the simplified internet hosting product in ASP.Web Core 6, you no more time have to use the Startup class. You can study far more about this in my previously short article in this article. Here’s how you would compose a common Application course in ASP.Net Core 6:

var builder = WebApplication.CreateBuilder(args)
// Add products and services to the container
builder.Providers.AddControllers()
var application = builder.Make()
// Configure the HTTP request pipeline
app.UseAuthorization()
application.MapControllers()
app.Operate()

Incorporate middleware in ASP.Internet Main 5

The pursuing code snippet demonstrates how you can increase a middleware component in ASP.Internet Main 5. In our case in point, we’ll insert the response compression middleware.

community class Startup

    community void Configure(IApplicationBuilder application)
   
        application.UseResponseCompression()
   

Increase middleware in ASP.Web Core 6

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

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

Insert routing in ASP.Internet Main 5

To insert an endpoint in ASP.Net Main 5, you can use the following code.

public class Startup

    general public void Configure(IApplicationBuilder app)
   
        application.UseRouting()
        app.UseEndpoints(endpoints =>
       
            endpoints.MapGet("/check", () => "This is a take a look at information.")
        )
   

Include routing in ASP.Net Main 6

You can add an endpoint in ASP.Internet Main 6 utilizing the subsequent code.

var builder = WebApplication.CreateBuilder(args)
var application = builder.Make()
application.MapGet("/exam", () => "This is a take a look at information.")
application.Run()

Note that in ASP.Net Core 6 you can add endpoints to WebApplication without possessing to make specific phone calls to the UseRouting or UseEndpoints extension approaches.

Increase products and services in ASP.Web Core 5

The pursuing code snippet illustrates how you can add services to the container in ASP.Net Core 5.

community class Startup

    community void ConfigureServices(IServiceCollection products and services)
   
        // Add crafted-in providers
        solutions.AddMemoryCache()
        services.AddRazorPages()
        providers.AddControllersWithViews()
        // Insert a custom made service
        expert services.AddScoped()
   

Incorporate providers in ASP.Net Main 6

To add solutions to the container in ASP.Internet Main 6, you can use the next code.

var builder = WebApplication.CreateBuilder(args)
// Increase built-in providers
builder.Companies.AddMemoryCache()
builder.Companies.AddRazorPages()
builder.Solutions.AddControllersWithViews()
// Include a custom services
builder.Expert services.AddScoped()
var application = builder.Build()

Exam an ASP.Internet Main 5 or ASP.Net Core 6 software

You can examination an ASP.Web Core 5 software making use of both TestServer or WebApplicationFactory. To test working with TestServer in ASP.Net Core 5, you can use the pursuing code snippet.

[Fact]
public async Activity GetProductsTest()

    applying var host = Host.CreateDefaultBuilder()
        .ConfigureWebHostDefaults(builder =>
       
            builder.UseTestServer()
                    .UseStartup()
        )
        .ConfigureServices(solutions =>
       
            providers.AddSingleton()
        )
        .Create()
    await host.StartAsync()
    var consumer = host.GetTestClient()
    var response = await client.GetStringAsync("/getproducts")
    Assert.Equal(HttpStatusCode.Alright, response.StatusCode)

The next code snippet shows how you can examination your ASP.Net Core 5 software employing WebApplicationFactory.

[Fact]
public async Task GetProductsTest()

    var application = new WebApplicationFactory()
        .WithWebHostBuilder(builder =>
       
            builder.ConfigureServices(products and services =>
           
                expert services.AddSingleton()
            )
        )
    var customer = software.CreateClient()
    var response = await consumer.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. 

Include a logging provider in ASP.Internet Core 5

Logging suppliers in ASP.Net Core are made use of to retailer logs. The default logging providers provided in ASP.Internet Main are the Debug, Console, EventLog, and EventSource logging vendors.

You can use the ClearProviders process to apparent all logging vendors and increase a specific logging supplier or your possess tailor made logging supplier. The adhering to code snippet illustrates how you can get rid of all ILoggerProvider scenarios and add the Console logging company in ASP.Web Core 5.

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

Include a logging company in ASP.Net Main 6

In ASP.Web Core 6, when you call WebApplication.CreateBuilder, it adds the Console, Debug, EventLog, and EventSource logging suppliers. The following code snippet shows how you can crystal clear the default logging providers and insert only the Console logging service provider in ASP.Net Main 6.

var builder = WebApplication.CreateBuilder(args)
//Crystal clear default logging provid ers
builder.Logging.ClearProviders()
//Code to incorporate expert services to the container
builder.Logging.AddConsole()
var app = builder.Develop()

The code illustrations supplied right here illustrate the diverse approaches we add middleware, routing, providers, and logging companies in ASP.Internet Main 5 and in ASP.Internet Core 6, as very well as variations in the Program course and testing. These snippets really should help you when performing with ASP.Net Core 6 apps, and get you off to a fantastic begin when you migrate your ASP.Web Core 5 apps to ASP.Net Core 6.

Copyright © 2022 IDG Communications, Inc.

[ad_2]

Supply website link