in

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

How to 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 write down to get your ASP.NET Core utility up and working. ASP.NET Core 6 makes a bit simpler to create a brand new net utility from scratch, in contrast with ASP.NET Core 5.But what if you wish to replace an ASP.NET Core 5 venture to ASP.NET Core 6? In that case, try to be conscious of the code you have to to write down emigrate ASP.NET Core 5 code to ASP.NET Core 6. This article presents a number of code samples that present how you are able to do this.To work with the code examples offered on this article, it is best to have Visual Studio 2022 put in in your system. If you don’t have already got a replica, you may obtain Visual Studio 2022 right here.Create an ASP.NET Core Web API venture in Visual Studio 2022First off, let’s create an ASP.NET Core venture in Visual Studio 2022. Following these steps will create a brand new ASP.NET Core Web API 6 venture in Visual Studio 2022:
Launch the Visual Studio 2022 IDE.
Click on “Create new project.”
In the “Create new project” window, choose “ASP.NET Core Web API” from the record of templates displayed.
Click Next.
In the “Configure your new project” window, specify the identify and site for the brand new venture.
Optionally test the “Place solution and project in the same directory” test field, relying in your preferences.
Click Next.
In the “Additional Information” window proven subsequent, make sure 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. Leave the “Authentication Type” set to “None” (default).
Ensure that the test bins “Enable Docker,” “Configure for HTTPS,” and “Enable Open API Support” are unchecked as we received’t be utilizing any of these options right here.
Click Create.
We’ll use this ASP.NET Core 6 Web API venture for instance 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 5The following code snippet illustrates what a typical Program class seems to be like in ASP.NET Core 5. public class Program      public static void Main(string[] args)             CreateHostBuilder(args).Build().Run();            public static IHostBuilder CreateHostBuilder(string[] args)             return Host.CreateDefaultBuilder(args).            ConfigureWebHostDefaults(x => x.UseStartup <Startup> ());      The Program class in ASP.NET Core 6With the introduction of the simplified internet hosting mannequin in ASP.NET Core 6, you now not have to make use of the Startup class. You can learn extra about this in my earlier article right here. Here’s how you’ll write a typical Program class in ASP.NET Core 6:var builder = WebUtility.CreateBuilder(args);// Add providers to the containerbuilder.Services.AddControllers();var app = builder.Build();// Configure the HTTP request pipelineapp.UseAuthorization();app.MapControllers();app.Run();Add middleware in ASP.NET Core 5The following 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 6To add a middleware element in ASP.NET Core 6, you need to use the next code.var builder = WebUtility.CreateBuilder(args);var app = builder.Build();app.UseResponseCompression();app.Run();Add routing in ASP.NET Core 5To add an endpoint in ASP.NET Core 5, you need to use the next code.public class Startup    public void Configure(IApplicationBuilder app)            app.UseRouting();        app.UseEndpoints(endpoints =>                    endpoints.MapGet(“/test”, () => “This is a test message.”);        );    Add routing in ASP.NET Core 6You can add an endpoint in ASP.NET Core 6 utilizing the next code.var builder = WebUtility.CreateBuilder(args);var app = builder.Build();app.MapGet(“/test”, () => “This is a test message.”);app.Run();Note that in ASP.NET Core 6 you may add endpoints to WebUtility with out having to make specific calls to the UseRouting or UseEndpoints extension strategies. Add providers in ASP.NET Core 5The following 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 6To add providers to the container in ASP.NET Core 6, you need to use the next code.var builder = WebUtility.CreateBuilder(args);// Add built-in servicesbuilder.Services.AddMemoryCache();builder.Services.AddRazorPages();builder.Services.AddControllersWithViews();// Add a customized servicebuilder.Services.AddScoped<IProductRepository, ProductRepository>();var app = builder.Build();Test an ASP.NET Core 5 or ASP.NET Core 6 utilityYou can check an ASP.NET Core 5 utility utilizing both TestServer or WebUtilityFactory. To check utilizing TestServer in ASP.NET Core 5, you need to use the next code snippet.[Fact]public async Task GetProductsTest()    utilizing var host = Host.CreateDefaultBuilder()        .ConfigureWebHostDefaults(builder =>                    builder.UseTestServer()                    .UseStartup<WebApplication1.Startup>();        )        .ConfigureServices(providers =>                    providers.AddSingleton<IProductService, MockProductService>();        )        .Build();    await host.StartAsync();    var shopper = host.GetTestConsumer();    var response = await shopper.GetStringAsync(“/getproducts”);    Assert.Equal(HttpStatusCode.OK, response.StandingCode);The following code snippet exhibits how one can check your ASP.NET Core 5 utility utilizing WebUtilityFactory. [Fact]public async Task GetProductsTest()    var utility = new WebUtilityFactory<Program>()        .WithWebHostBuilder(builder =>                    builder.ConfigureServices(providers =>                            providers.AddSingleton<IProductService, MockProductService>();            );        );    var shopper = utility.CreateConsumer();    var response = await shopper.GetStringAsync(“/getproducts”);    Assert.Equal(HttpStatusCode.OK, response.StandingCode);You can use the identical code to check utilizing TestServer or WebUtilityFactory in .NET 5 and .NET 6. Add a logging supplier in ASP.NET Core 5Logging 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 can use the ClearSuppliers methodology to clear all logging suppliers and add a selected logging supplier or your personal customized logging supplier. The following 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.ClearSuppliers();         logging.AddConsole();      )      .ConfigureWebHostDefaults(netBuilder =>         netBuilder.UseStartup<Startup>();      );Add a logging supplier in ASP.NET Core 6In ASP.NET Core 6, whenever you name WebUtility.CreateBuilder, it provides the Console, Debug, EventLog, and EventSource logging suppliers. The following 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 = WebUtility.CreateBuilder(args);//Clear default logging providersbuilder.Logging.ClearSuppliers();//Code so as to add providers to the containerbuilder.Logging.AddConsole();var app = builder.Build();The code examples offered 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 to 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.

What do you think?

Written by Aj Singh

Leave a Reply

Your email address will not be published.

Nifty Newsletter, June 29–July 5

Nifty Newsletter, June 29–July 5

Untitled-13

India vs England, 1st T20I: Hardik Pandya stars as India beat England by 50 runs | Cricket News