April 15, 2024

hopeforharmonie

Step Into The Technology

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

6 min read

[ad_1]

Microsoft’s ASP.Internet Main 6, which has been offered for creation use due to the fact November 8, introduces a simplified hosting product that minimizes the boilerplate code that you would normally have to have to create to get your ASP.Web Core application up and managing. ASP.Web Core 6 helps make a little bit less difficult to make a new website application from scratch, in contrast with ASP.Net Main 5.

But what if you want to update an ASP.Net Core 5 venture to ASP.Net Core 6? In that situation, you ought to be informed of the code you will require to publish to migrate ASP.Net Core 5 code to ASP.Internet Core 6. This short article offers several code samples that present how you can do this.

To do the job with the code illustrations furnished in this article, you should really have Visual Studio 2022 put in in your process. If you never presently have a duplicate, you can obtain Visible Studio 2022 here.

Develop an ASP.Web Core Web API project in Visible Studio 2022

Initially off, let’s create an ASP.Net Main venture in Visual Studio 2022. Following these ways will generate a new ASP.Web Main World wide web API 6 venture in Visual Studio 2022:

  1. Start the Visible Studio 2022 IDE.
  2. Simply click on “Create new task.”
  3. In the “Create new project” window, select “ASP.Internet Main Website API” from the listing of templates shown.
  4. Click Upcoming.
  5. In the “Configure your new project” window, specify the name and locale for the new project.
  6. Optionally examine the “Place answer and task in the exact directory” check out box, depending on your preferences.
  7. Simply click Following.
  8. In the “Additional Information” window demonstrated next, make sure that the look at box that says “Use controllers…” is checked, as we’ll be making use of controllers instead of negligible APIs in this example. Depart the “Authentication Type” set to “None” (default).
  9. Ensure that the look at bins “Enable Docker,” “Configure for HTTPS,” and “Enable Open up API Support” are unchecked as we will not be employing any of people features below.
  10. Click on Build.

We’ll use this ASP.Internet Core 6 World-wide-web API undertaking to illustrate migrations of ASP.Internet Main 5 code to ASP.Internet Main 6 in the subsequent sections of this short article.

The System course in ASP.Net Core 5

The adhering to code snippet illustrates what a regular Software class seems like in ASP.Web Main 5.

community course Plan

      community static void Major(string[] args)
            CreateHostBuilder(args).Establish().Operate()
     
      community static IHostBuilder CreateHostBuilder(string[] args)
            return Host.CreateDefaultBuilder(args).
            ConfigureWebHostDefaults(x => x.UseStartup ())
     

The System class in ASP.Internet Main 6

With the introduction of the simplified internet hosting product in ASP.Web Core 6, you no for a longer period have to use the Startup class. You can browse additional about this in my earlier article here. Here’s how you would publish a usual Program class in ASP.Internet Core 6:

var builder = WebApplication.CreateBuilder(args)
// Insert companies to the container
builder.Services.AddControllers()
var application = builder.Establish()
// Configure the HTTP ask for pipeline
application.UseAuthorization()
app.MapControllers()
app.Operate()

Insert middleware in ASP.Net Main 5

The next code snippet exhibits how you can include a middleware component in ASP.Web Main 5. In our instance, we’ll insert the reaction compression middleware.

community course Startup

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

Insert middleware in ASP.Web Core 6

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

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

Increase routing in ASP.Web Main 5

To incorporate an endpoint in ASP.Web Core 5, you can use the pursuing code.

community class Startup

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

Insert routing in ASP.Internet Core 6

You can increase an endpoint in ASP.Internet Core 6 utilizing the following code.

var builder = WebApplication.CreateBuilder(args)
var app = builder.Build()
app.MapGet("/check", () => "This is a test concept.")
application.Operate()

Observe that in ASP.Web Core 6 you can include endpoints to WebApplication with no possessing to make explicit calls to the UseRouting or UseEndpoints extension strategies.

Increase companies in ASP.Web Main 5

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

community class Startup

    public void ConfigureServices(IServiceCollection products and services)
   
        // Insert created-in products and services
        solutions.AddMemoryCache()
        providers.AddRazorPages()
        services.AddControllersWithViews()
        // Incorporate a custom made support
        providers.AddScoped()
   

Increase services in ASP.Internet Core 6

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

var builder = WebApplication.CreateBuilder(args)
// Incorporate developed-in solutions
builder.Providers.AddMemoryCache()
builder.Providers.AddRazorPages()
builder.Expert services.AddControllersWithViews()
// Add a personalized support
builder.Providers.AddScoped()
var application = builder.Make()

Test an ASP.Web Main 5 or ASP.Net Main 6 application

You can examination an ASP.Web Core 5 application using possibly TestServer or WebApplicationFactory. To test employing TestServer in ASP.Web Main 5, you can use the following code snippet.

[Fact]
public async Task GetProductsTest()

    using var host = Host.CreateDefaultBuilder()
        .ConfigureWebHostDefaults(builder =>
       
            builder.UseTestServer()
                    .UseStartup()
        )
        .ConfigureServices(products and services =>
       
            services.AddSingleton()
        )
        .Construct()
    await host.StartAsync()
    var customer = host.GetTestClient()
    var response = await consumer.GetStringAsync("/getproducts")
    Assert.Equivalent(HttpStatusCode.Alright, reaction.StatusCode)

The pursuing code snippet exhibits how you can exam your ASP.Web Core 5 software making use of WebApplicationFactory.

[Fact]
general public async Endeavor GetProductsTest()

    var application = new WebApplicationFactory()
        .WithWebHostBuilder(builder =>
       
            builder.ConfigureServices(companies =>
           
                solutions.AddSingleton()
            )
        )
    var consumer = application.CreateClient()
    var response = await client.GetStringAsync("/getproducts")
    Assert.Equal(HttpStatusCode.Okay, response.StatusCode)

You can use the same code to examination applying TestServer or WebApplicationFactory in .Net 5 and .Internet 6. 

Add a logging provider in ASP.Web Main 5

Logging companies in ASP.Web Core are employed to shop logs. The default logging vendors provided in ASP.Net Main are the Debug, Console, EventLog, and EventSource logging companies.

You can use the ClearProviders technique to apparent all logging suppliers and increase a precise logging provider or your individual personalized logging company. The following code snippet illustrates how you can eliminate all ILoggerProvider circumstances and include the Console logging company in ASP.Internet Core 5.

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

Add a logging provider in ASP.Web Main 6

In ASP.Web Main 6, when you get in touch with WebApplication.CreateBuilder, it provides the Console, Debug, EventLog, and EventSource logging providers. The next code snippet demonstrates how you can clear the default logging providers and include only the Console logging supplier in ASP.Internet Main 6.

var builder = WebApplication.CreateBuilder(args)
//Clear default logging providers
builder.Logging.ClearProviders()
//Code to add companies to the container
builder.Logging.AddConsole()
var app = builder.Develop()

The code examples presented here illustrate the distinct techniques we add middleware, routing, services, and logging suppliers in ASP.Web Core 5 and in ASP.Internet Core 6, as well as dissimilarities in the Plan class and screening. These snippets need to help you when operating with ASP.Internet Main 6 applications, and get you off to a excellent start out when you migrate your ASP.Web Main 5 programs to ASP.Net Main 6.

Copyright © 2022 IDG Communications, Inc.

[ad_2]

Supply connection

hopeforharmonie.co.uk | Newsphere by AF themes.