Friday, April 26, 2024
HomeC#Upgrading an ASP.NET Core Internet API Mission to .NET 6 – csharp.christiannagel.com

Upgrading an ASP.NET Core Internet API Mission to .NET 6 – csharp.christiannagel.com


Upgrading an ASP.NET Core 5 utility to .NET 6, all what must be finished is to alter the venture file for .NET 6, and replace the NuGet packages to the brand new variations, and also you’re finished and might construct and run the appliance. Nevertheless, to benefit from new options, and scale back the variety of supply code strains, some issues might be modified – as proven on this article.

Maze

The pattern utility

The unique pattern utility is a straightforward Internet API applied with ASP.NET Core 5.0, utilizing EF Core to entry a database, and manipulate E-book objects.

The Program class with the Principal methodology makes use of the Host class to invoke the CreateDefaultBuilder methodology for the default configuration of the DI container, logging, and configuration – and with ASP.NET Core, the Startup class.

Program class

The next code snippet exhibits part of the Startup class (with out the utilizing directives and the namespace definition for readability) the place the appliance companies are registered with the DI container, and the middleware is configured.

Startup class

The BooksContext class defines the mapping for the E-book file to the database utilizing EF Core.

BooksContext

With the BooksController class, the BooksContext is injected to entry it with the general public strategies which have attributes equivalent to HttpGet and HttpPost annotated to make use of these strategies calling the totally different HTTP verbs. The next code snippet exhibits a small a part of the BooksController implementation.

BooksController

With the venture configuration file BooksAPI.csproj, the appliance has the <TargetFramework> set to dotnet5, and NuGet packages Microsoft.EntityFramework.SqlServer, Microsoft.EntityFrameworkCore.Instruments, Microsoft.EntityFrameworkCore.Design, and Swashbuckle.AspNetCore packages appropriate with .NET 5 configured – and it has nullable enabled.

Nullable reference sorts can be found since C# 8, simply with new .NET Core 6 tasks it’s a default confinguration. It helps decreasing nullable points additionally with older venture sorts.

All what must be finished to run the present .NET 5 utility with .NET 6 is to alter the <TargetFramework> to dotnet6, and replace the NuGet packages (as proven within the following determine). The applying might be rebuild and runs with out every other modifications wanted.

Package Updates with Visual Studio

File-Scoped Namespaces

To benefit of C# 10 and .NET 6, let’s begin altering the code-base to make use of new options. The primary change finished within the utility is to chagne the namespace declarations to file-scoped namespaces. This reduces the horizontal characters wanted which helps for higher readability – and removes a number of code strains.

Utilizing the latest model of Visible Studio 2022 you simply want so as to add a ; add the tip of the namespace declaration (e.g. namespace BooksAPI;), and the refactoring occurs mechanically. This alteration is completed with the recordsdata Program.cs, Startup.cs, BooksContext.cs, and BooksController.cs.

File-Scoped Namespace

World Usings

Some utilizing declarations which can be wanted throughout totally different recordsdata might be eliminated with C# 10. With this small utility, an excessive is completed by specifying the namespaces wanted within the full utility throughout the Program.cs file as proven within the following code snippet.

Global Usings

You need to use a distinct strategy and simply use world utilizing for generally used namespaces within the utility, and use the standard utilizing with the supply code recordsdata the place different namespaces are required. You can even specify a distinct supply code file (e.g. GlobalUsings.cs) the place to specify the world utilizing statements.

Implicit Usings

The following step is to take away among the required namespaces utterly from the supply code. This may be finished by enabling implicit usings within the venture configuration file as proven within the subsequent determine.

Configure Implicit Usings

Relying on the SDK used, totally different namespaces are than added as world utilizing by default. Utilizing the Internet SDK, just some namespaces are left that should be included as proven within the following code snippet.

Remaining Namespaces required with Implicit Usings

Internet Software Builder

Up to now you’ve seen some small C# options which enhance the productiveness by decreasing the variety of code strains wanted. Now let’s step over to enhancements with ASP.NET Core. To get extra benefits of C# top-level statements, the WebApplication along with WebApplicationBuilder can be utilized to configure DI, logging, configuration, and middleware. This removes the necessity for the Startup class.

Examine the next code snippet with code modifications to do away with the Startup class. First, Providers property of the WebApplicationBuilder is used to configure the DI container. With the earlier implementation, the ConfigureServices methodology was used. With the Startup class, AddDbContext was used so as to add the EF Core context to the DI container. For top-level statements, the EF Core workforce created a brand new methodology for SQL Server – AddSqlServer – which simply wants a connection string as a substitute of specifying choices with a lambda expression. Configuration for the connection string is learn utilizing the Configuration property of the WebApplicationBuilder.

Invoking the Construct methodology of the WebApplicationBuilder returns the WebApplication class. Earlier than invokding the Run methodology, with UseXXX strategies, middleware is configured. That is the earlier implementation of the Configure methodology with the Startup class.

Startup with WebApplication

Eliminating the Startup class, eradicating some boiler-plate code, the appliance runs like earlier than.

Relying on the scale of your service, you may cease at this stage updating the supply code for ASP.NET Core 6 – preserving the controller class prefer it was earlier than (with the minor modifications for implicit usings, world usings, and file-scoped namespaces). In case your service is small (Microservice?), you proceed with the following step and use the Minimal API to do away with the controller class as effectively.

Making a Minimal API and Extensions with Lambdas

With the Minimal API, you may map the routes for the implementation of the API immediately utilizing the WebApplication class – the BooksController is now not wanted. Thus, the AddControllers methodology might be eliminated as a result of the DI companies for the controllers are now not wanted, and the middleware for the controllers, UseControllers might be eliminated as effectively. To nonetheless have OpenAPI configuration, the companies wanted by swagger should be configured with the DI container. That is finished invoking the tactic AddEndpointsApiExplorer.

The routes can now be mapped with the MapGet, MapPost, MapPut, and MapDelete strategies. With ASP.NET Core 6, a brand new overload of those strategies is obtainable. The code snippet beneath exhibits the MapPost methodology – mapping a HTTP POST methodology with the route /api/books to this methodology. Creating a number of of those strategies spares making a controller.

Minimal API

The brand new overloads of those strategies, have a Delegate parameter sort as a substitute of the RequestDelegate with .NET 6. This permits passing a delegate or lambda expression with parameters and return sorts as wanted. With the code snippet, the BooksContext parameter is injected from the DI container, the E-book parameter will get its worth from the physique of the HTTP request. Utilizing C# 10, you may specify attributes with parameters of lambda expressions. The attribute [FromServices] and [FromBody] would apply to the parameters of this methodology. With the default binding sources for route values, question strings, HTTP header and physique, and dependency injection companies, it’s not essential to specify attributes.

One other function utilizing the Minimal API that’s proven right here is the Outcomes manufacturing unit class that gives a simple technique to return totally different HTTP outcomes.

Permitting attributes with parameters of lambdas is among the C# 10 extensions for lambdas. One other is that it’s allowed to specify the return sort. That is mandatory if the return sort can’t be deducted immediately from the returned worth, e.g. if the return sort must be of a base class or an interface.

The pattern utility out there with the GitHub repo implements strategies for studying and writing e-book knowledge from the database.

The pattern utility makes use of totally different strategies for all of the HTTP verbs used. The InstantAPIs library (at the moment in very early phases) tries to make this even simpler: only one methodology is required to supply a CRUD REST API accessing a database utilizing an EF Core context. See the hyperlink beneath.

Lambda enhancements with C# 10 helpful for Minimal APIs:

  • Attributes with lambda parameters
  • Explicitly declaring return sorts
  • Pure delegate sorts

What’s a pure delegate sort? As proven within the subsequent determine, earlier than C# 10 it was not doable to assign a lambda expression to a variable of sort Delegate or to make use of var with out casting the lambda expression. With the pure delegate sort of C# 10, this has been made doable.

Natural Delegates

Take away

To replace an .NET 5 Internet API utility, all what’s wanted is to alter the .NET model and replace the NuGet packages. Nevertheless, you may benefit from new options. With .NET 6, you may implement the identical performance with lots much less boilerplate code. C# 10 provides nice options to cut back boilerplate code. Right here you’ve seen file-scoped namespaces, world usings, implicit usings, and pure delegate sorts. Utilizing the Minimal API with .NET 6, the boilerplate code wanted to create REST APIs has been decreased. .NET and C# options properly combine.

Get pleasure from studying and programming!

Christian

Should you preferred this text – it will be nice when you present help shopping for a espresso.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments