[ad_1]

Microsoft’s ASP.Internet Core 6, which has been offered for production use considering the fact that November 8, introduces a simplified web hosting design that cuts down the boilerplate code that you would normally will need to write to get your ASP.Web Main application up and managing. ASP.Net Main 6 tends to make a bit simpler to create a new internet application from scratch, as opposed with ASP.Internet Main 5.

But what if you want to update an ASP.Internet Main 5 task to ASP.Web Main 6? In that situation, you ought to be aware of the code you will need to have to create to migrate ASP.Web Main 5 code to ASP.Net Core 6. This post presents numerous code samples that demonstrate how you can do this.

To do the job with the code examples delivered in this report, you ought to have Visible Studio 2022 set up in your program. If you really do not already have a copy, you can obtain Visual Studio 2022 listed here.

Generate an ASP.Web Core Net API challenge in Visible Studio 2022

Very first off, let’s generate an ASP.Web Main venture in Visual Studio 2022. Next these measures will produce a new ASP.Internet Core World wide web API 6 job in Visual Studio 2022:

  1. Start the Visual Studio 2022 IDE.
  2. Simply click on “Create new job.”
  3. In the “Create new project” window, find “ASP.Net Main Internet API” from the record of templates exhibited.
  4. Simply click Up coming.
  5. In the “Configure your new project” window, specify the name and spot for the new project.
  6. Optionally test the “Place solution and task in the exact directory” check out box, dependent on your preferences.
  7. Click Future.
  8. In the “Additional Information” window revealed subsequent, guarantee that the look at box that suggests “Use controllers…” is checked, as we’ll be making use of controllers as an alternative of negligible APIs in this illustration. Depart the “Authentication Type” established to “None” (default).
  9. Assure that the verify bins “Enable Docker,” “Configure for HTTPS,” and “Enable Open up API Support” are unchecked as we won’t be using any of those attributes listed here.
  10. Click Create.

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

The Software class in ASP.Internet Main 5

The next code snippet illustrates what a normal Plan class appears like in ASP.Internet Main 5.

general public class 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 Plan class in ASP.Web Core 6

With the introduction of the simplified web hosting model in ASP.Net Main 6, you no longer have to use the Startup class. You can read through extra about this in my before post below. Here’s how you would publish a normal Software course in ASP.Internet Core 6:

var builder = WebApplication.CreateBuilder(args)
// Add providers to the container
builder.Expert services.AddControllers()
var app = builder.Make()
// Configure the HTTP ask for pipeline
application.UseAuthorization()
app.MapControllers()
application.Operate()

Add middleware in ASP.Net Core 5

The subsequent code snippet demonstrates how you can add a middleware part in ASP.Net Main 5. In our illustration, we’ll include the reaction compression middleware.

public class Startup

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

Add middleware in ASP.Net Main 6

To insert a middleware ingredient in ASP.Web Core 6, you can use the adhering to code.

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

Incorporate routing in ASP.Web Main 5

To include an endpoint in ASP.Net Core 5, you can use the pursuing code.

general public class Startup

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

Increase routing in ASP.Net Core 6

You can include an endpoint in ASP.Net Main 6 employing the adhering to code.

var builder = WebApplication.CreateBuilder(args)
var app = builder.Develop()
application.MapGet("/test", () => "This is a take a look at message.")
application.Operate()

Note that in ASP.Web Core 6 you can insert endpoints to WebApplication with no getting to make express calls to the UseRouting or UseEndpoints extension approaches.

Add products and services in ASP.Web Main 5

The adhering to code snippet illustrates how you can insert companies to the container in ASP.Internet Main 5.

public course Startup

    public void ConfigureServices(IServiceCollection products and services)
   
        // Incorporate built-in companies
        companies.AddMemoryCache()
        products and services.AddRazorPages()
        services.AddControllersWithViews()
        // Insert a tailor made support
        expert services.AddScoped()
   

Insert providers in ASP.Internet Core 6

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

var builder = WebApplication.CreateBuilder(args)
// Include constructed-in solutions
builder.Expert services.AddMemoryCache()
builder.Providers.AddRazorPages()
builder.Solutions.AddControllersWithViews()
// Insert a customized support
builder.Solutions.AddScoped()
var app = builder.Build()

Examination an ASP.Web Main 5 or ASP.Web Main 6 software

You can test an ASP.Internet Core 5 application making use of either TestServer or WebApplicationFactory. To examination making use of TestServer in ASP.Net Core 5, you can use the following code snippet.

[Fact]
public async Process GetProductsTest()

    using var host = Host.CreateDefaultBuilder()
        .ConfigureWebHostDefaults(builder =>
       
            builder.UseTestServer()
                    .UseStartup()
        )
        .ConfigureServices(services =>
       
            companies.AddSingleton()
        )
        .Build()
    await host.StartAsync()
    var customer = host.GetTestClient()
    var reaction = await client.GetStringAsync("/getproducts")
    Assert.Equivalent(HttpStatusCode.Okay, response.StatusCode)

The subsequent code snippet shows how you can examination your ASP.Net Main 5 application using WebApplicationFactory.

[Fact]
community async Job GetProductsTest()

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

You can use the identical code to take a look at applying TestServer or WebApplicationFactory in .Internet 5 and .Internet 6. 

Increase a logging supplier in ASP.Web Main 5

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

You can use the ClearProviders strategy to distinct all logging suppliers and include a specific logging supplier or your own personalized logging provider. The next code snippet illustrates how you can eliminate all ILoggerProvider instances and incorporate the Console logging supplier in ASP.Net Main 5.

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

Add a logging company in ASP.Net Main 6

In ASP.Net Main 6, when you contact WebApplication.CreateBuilder, it provides the Console, Debug, EventLog, and EventSource logging vendors. The pursuing code snippet exhibits how you can apparent the default logging companies and increase only the Console logging provider in ASP.Web Core 6.

var builder = WebApplication.CreateBuilder(args)
//Distinct default logging vendors
builder.Logging.ClearProviders()
//Code to incorporate products and services to the container
builder.Logging.AddConsole()
var application = builder.Create()

The code examples delivered here illustrate the various techniques we insert middleware, routing, expert services, and logging companies in ASP.Net Main 5 and in ASP.Internet Main 6, as effectively as distinctions in the Program course and tests. These snippets need to assistance you when operating with ASP.Internet Core 6 applications, and get you off to a excellent commence when you migrate your ASP.Internet Main 5 purposes to ASP.Web Main 6.

Copyright © 2022 IDG Communications, Inc.

[ad_2]

Supply url