Latest updates and features in .NET 7
NET 7 is the successor to .NET 6 and focuses on being unified, modern, simple, and fast. .NET 7 will be supported for 18 months as a standard-term support (STS) release. .NET 7 was released on November 8, 2022 and is the latest version of the .NET platform. It includes a number of new features and improvements, including:
- C# 11: C# 11 includes a number of new features, such as global using directives, file-scoped namespaces, and record structs.
- Performance improvements: .NET 7 includes a number of performance improvements, such as faster startup times and lower memory usage.
- New features for cloud-native development: .NET 7 includes a number of new features for cloud-native development, such as support for HTTP/3 and improvements to minimal APIs.
- New features for desktop development: .NET 7 includes a number of new features for desktop development, such as support for WinUI 3.1 and improvements to Windows Presentation Foundation (WPF).
- New features for mobile development: .NET 7 includes a number of new features for mobile development, such as support for .NET MAUI and improvements to Xamarin.Forms.
C# 11 features in .NET 7
C# 11 includes a number of new features, such as:
- Global using directives: Global using directives allow you to import namespaces at the top of your code file, so that you don’t have to import them in each class.
- File-scoped namespaces: File-scoped namespaces allow you to define namespaces that are only accessible within the current file.
- Record structs: Record structs are a new type of struct that is specifically designed for storing data. They are similar to regular structs, but they have some additional features, such as automatic property generation and initialization.
- Init-only setters: Init-only setters allow you to set properties only once, during object creation or initialization.
- Required properties: Required properties must be set before the object is used.
- Asynchronous streams: Asynchronous streams allow you to read and write data asynchronously, without blocking the thread.
- Improvements to generic math: Generic math has been improved in C# 11, making it easier to write generic math code.
- New APIs for pattern matching: C# 11 includes new APIs for pattern matching, making it more powerful and easier to use.
Performance improvements in .NET 7
.NET 7 includes a number of performance improvements, such as:
- Faster startup times: .NET 7 has faster startup times than previous versions of .NET. This is due to a number of improvements, such as precompiling more of the runtime and using a new JIT compiler.
- Lower memory usage: .NET 7 uses less memory than previous versions of .NET. This is due to a number of improvements, such as reducing the size of the runtime and using a new garbage collector.
- Improved performance of regular expressions: The regular expression library in .NET 7 has been improved, resulting in significant performance gains for many regular expressions.
- Improved performance of ASP.NET Core: ASP.NET Core in .NET 7 has a number of performance improvements, such as faster routing and caching.
New features for cloud-native development in .NET 7
.NET 7 includes a number of new features for cloud-native development, such as:
- Support for HTTP/3: .NET 7 supports HTTP/3, the latest version of the HTTP protocol. HTTP/3 offers a number of benefits over HTTP/2, such as improved performance and reliability.
- Improvements to minimal APIs: Minimal APIs in .NET 7 have been improved, making them easier to use and more powerful. For example, minimal APIs now support file uploads and rate limiting.
- Improvements to container support: .NET 7 includes a number of improvements to container support, such as the ability to publish directly to containers and to use central package management with NuGet.
New features for desktop development in .NET 7
.NET 7 includes a number of new features for desktop development, such as:
- Support for WinUI 3.1: .NET 7 supports WinUI 3.1, the latest version of the Windows UI platform. WinUI 3.1 includes a number of new features, such as support for Fluent Design and XAML islands.
- Improvements to Windows Presentation Foundation (WPF): WPF in .NET 7 has a number of improvements, such as support for dark mode and variable fonts.
New features for mobile development in .NET 7
.NET 7 includes a number of new features for mobile development, such as:
- Support for .NET MAUI: .NET MAUI is a new cross-platform UI framework that allows you to build native mobile and desktop applications from a single codebase. .NET MAUI is still in preview, but it is expected to be released in the near future.
- Improvements to Xamarin.Forms: Xamarin.Forms in .NET 7 has a number of improvements, such as support for new platform features and performance enhancements.
For more information, please head over to our Hire .NET Developer page and to develop a website using ASP.NET, Hire .NET Developer at HK Infosoft – we are destined to provide you with an innovative solution using the latest technology stacks. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”.
Content Source:
- DotNet Official Documentation
How to build a RESTful Web API using .NET Core 6
.NET 6 is the latest LTS (Long Term Support) release currently and will be supported until November 12, 2024.
This API will manage movie records stored in a relational database (SQL Server) as described in the table below:
Pic courtesy: medium.com
The sections of this post will be as follows:
- What is REST?
- Creating a Web API Project
- Adding a Model
- Adding a Database Context
- Creating Database with Migrations
- Creating API Controller and Methods
You will need the following tools installed on your computer:
- Visual Studio 2022
- .NET 6.0 SDK
- Microsoft SQL Server Express
What is REST?
RESTful APIs conform to the REST architectural style.
REST, or REpresentational State Transfer, is an architectural style for providing standards between computer systems on the web, making it easier for systems to communicate with each other.
REST relies on client-server relationship. This essentially means that client application and server application must be able to evolve separately without any dependency on each other.
REST is stateless. That means the communication between the client and the server always contains all the information needed to perform the request. There is no session state in the server, it is kept entirely on the client’s side.
REST provides a uniform interface between components. Resources expose directory structure-like URIs.
REST is not strictly related to HTTP, but it is most commonly associated with it. There are four basic HTTP verbs we use in requests to interact with resources in a REST system:
- GET— retrieve a specific resource (by id) or a collection of resources
- POST— create a new resource
- PUT— update a specific resource (by id)
- DELETE— remove a specific resource by id
In a REST system, representations transfer JSON or XML to represent data objects and attributes.
REST has had such a large impact on the Web that it has mostly displaced SOAP-based interface design because it’s a considerably simpler style to use.
Creating a Web API Project
Open Visual Studio 2022 and select Create a new project and then select ASP.NET Core Web API:
Pic courtesy: medium.com
and give a name to your project in the following screen and then click Next.
In the next screen, select .NET 6.0 as the framework and click Create:
Pic courtesy: medium.com
At this point you have a starter project as follows:
Pic courtesy: medium.com
In the Program.cs you can see that Swagger support is added automatically to your project:
Pic courtesy: medium.com
And also Swashbuckle.AspNetCore NuGet package is added as a dependency.
Now, let’s run (Ctlr+F5) the project to see the default output. When the browser opens and the Swagger UI is shown, select the GET method in the WeatherForecast part and then select Try It Out and Execute:
Pic courtesy: medium.com
Also, you can use the curl URL shown in the Swagger UI for this method and see the result of the URL in the browser:
Pic courtesy: medium.com
When you run the application, the default URL comes from the launchSettings.json:
Pic courtesy: medium.com
And the result values come from the GET method of the WeatherForecastController:
Pic courtesy: medium.com
As you see, values here are hard coded and randomness is added to generate different values.
In your Web API, you will create your own records in an SQL server database and will be able to view, update and delete them through REST API endpoints.
Adding a Model
Now, you will implement your data model class.
In Solution Explorer, right-click the project. Select Add -> New Folder and name the folder Models.
Then right-click the Models folder and select Add->Class. Name the class Movie.cs and click Add.
Next, add the following properties to the class:
Pic courtesy: medium.com
The Id field is required by the database for the primary key.
Entity Framework Core
You will use your model with Entity Framework Core (EF Core) to work with a database.
EF Core is an object-relational mapping (ORM) framework that simplifies the data access code. Model classes don’t have any dependency on EF Core. They just define the properties of the data that will be stored in the database.
In this post, you will write the model classes first and EF Core will create the database. This is called Code First Approach.
Let’s add the EF Core NuGet packages to the project. Right-click on the project and select Manage NuGet Packages… and then install the following packages:
Pic courtesy: medium.com
Adding a Database Context
The database context is the main class that coordinates Entity Framework functionality for a data model. This class is created by deriving from Microsoft.EntityFrameworkCore.DbContext class.
Now, right-click the Models folder and select Add ->Class. Name the class MovieContext and click Add. Then add the following code to the class:
Pic courtesy: medium.com
The preceding code creates a DbSet<Movie> property for the entity set.
In Entity Framework terminology, an entity set typically corresponds to a database table and an entity corresponds to a row in the table.
The name of the connection string is passed into the context by calling a method on a DbContextOptions object. For local development, the ASP.NET Core configuration system reads the connection string from the appsettings.json file.
We need to add our connection string to the appsettings.json. You will use the local SQL server instance in your machine and you can define the connection string as follows:
Pic courtesy: medium.com
You can change the database name if you want.
Dependency Injection
ASP.NET Core is built with Dependency Injection (DI). Services (such as the EF Core DB context) are registered with DI during application startup. Components that require these services are provided with these services via constructor parameters.
Now, you will register your database context to the built-in IOC container. Add the following code to Program.cs:
Pic courtesy: medium.com
Creating Database with Migrations
Now, you will create the database using the EF Core Migrations feature.
Migrations lets us create a database that matches our data model and update the database schema when our data model changes.
First, you will add an initial Migration.
Open Tools -> NuGet Package Manager > Package Manager Console(PMC) and run the following command in the PMC:
Add-Migration Initial
The Add-Migration command generates code to create the initial database schema which is based on the model specified in the MovieContext class. The Initial argument is the migration name and any name can be used.
After running the command, a migration file is created under the Migrations folder:
Pic courtesy: medium.com
As the next step, run the following command in the PMC:
Update-Database
The Update-Database command runs the Up method in the Migrations/{time-stamp}_Initial.cs file, which creates the database.
Now, you will check the database created. Open View -> SQL Server Object Explorer.
You will see the newly created database as below:
Pic courtesy: medium.com
As you see, the Movie table and the Migrations History table are created automatically. Then a record is inserted into the migration history table to show the executed migrations on the database.
Creating API Controller and Methods
In this section, you will create the Movies API Controller and add the methods to it, and also will test those methods.
Let’s add the controller first. Right-click on the Controller folder and select Add -> Controller.. and then select API Controller – Empty as below:
Pic courtesy: medium.com
Click Add and give a name to your controller on the next screen.
Pic courtesy: medium.com
MoviesController is created as below:
Pic courtesy: medium.com
As you see, the class is decorated with the [ApiController] attribute. This attribute indicates that the controller responds to web API requests.
MoviesController class inherits from ControllerBase.
Next, we will inject the database context mentioned in the previous section through the constructor of the controller. Add the following code:
Pic courtesy: medium.com
Now, you will add CRUD (create, read, update, and delete) action methods to the controller. Let’s start with the GET methods.
GET Method
Add the following code to the MoviesController:
Pic courtesy: medium.com
GetMovies method returns all the movies and GetMovie(int id) method returns the movie having the Id given as input. They are decorated with the [HttpGet] attribute which denotes that a method responds to an HTTP GET request.
These methods implement two GET endpoints:
- GET /api/Movies
- GET /api/Movies/{id}
You can test the app by calling the two endpoints from a browser as follows:
- https://localhost:{port}/api/movies
- https://localhost:{port}/api/movies/{id}
The return type of the GetMovie methods is ActionResult<T> type. ASP.NET Core automatically serializes the object to JSON and writes the JSON into the body of the response message. The response code for this return type is 200, assuming there are no unhandled exceptions. Unhandled exceptions are translated into 5xx errors.
Routing and URL Paths
The URL path for each method is constructed as follows:
Start with the template string in the controller’s Route attribute (Route(“api/[controller]”)). Then replace [controller] with the name of the controller, which by convention is the controller class name minus the Controller suffix. For this sample, the controller class name is MoviesController, so the controller name is movies.
ASP.NET Core routing is case insensitive.
Testing the GetMovie Method
Now you will test these endpoints. Before that, let’s insert some movie records into your table.
Go to the SQL Server Object Explorer and right-click the Movies table and select View Data:
Pic courtesy: medium.com
Then add some movie records manually to the table:
Pic courtesy: medium.com
You do not need to add data for the Id column as SQL Server automatically handles this for us.
Now, you can test the GET endpoints. Start (Ctlr+F5) the application:
Pic courtesy: medium.com
Select the first GET method and click Try it out -> Execute:
Pic courtesy: medium.com
This shows all of the movies in the application.
Next, click the second GET method and click Try it out and enter one of the Ids above in the id field and click Execute:
Pic courtesy: medium.com
If no item matches the requested Id, the method returns a 404 NotFound error code.
Pic courtesy: medium.com
POST Method
Add the following code to the MoviesController:
Pic courtesy: medium.com
PostMovie method creates a movie record in the database. The preceding code is an HTTP POST method, as indicated by the [HttpPost] attribute. The method gets the value of the movie record from the body of the HTTP request.
The CreatedAtAction method:
- Returns an HTTP201 status code, if successful. HTTP 201 is the standard response for an HTTP POST method that creates a new resource on the server.
- Adds a Locationheader to the response. The Location header specifies the URI of the newly created movie record.
- References the GetMovieaction to create the Location header’s URI.
Testing the PostMovie Method
Start the application and then select the POST method in the Movies section.
Click Try it out and enter the movie information that you want to add in the request body:
Pic courtesy: medium.com
and click Execute.
Response status code is 201 (Created) and a location header is added to the response as seen below:
Pic courtesy: medium.com
You can paste this location URL in the browser and see the response there too:
Pic courtesy: medium.com
Also, you can check this record from the Movies table in your local database:
Pic courtesy: medium.com
PUT Method
Add the following code to the MoviesController:
Pic courtesy: medium.com
PutMovie method updates the movie record with the given Id in the database. The preceding code is an HTTP PUT method, as indicated by the [HttpPut] attribute. The method gets the value of the movie record from the body of the HTTP request. You need to supply the Id both in the request URL and the body and they have to match. According to the HTTP specification, a PUT request requires the client to send the entire updated entity, not just the changes.
The response is 204 (No Content) if the operation is successful.
Testing the PutMovie Method
Start the application and then select the PUT method in the Movies section.
Click Try it out and enter the movie information that you want to update in the request body and the Id of the movie in the id field:
Pic courtesy: medium.com
and then click Execute.
Pic courtesy: medium.com
We can check the updated state of the movie from GET method with Id in the Swagger UI or directly from the browser as below:
Pic courtesy: medium.com
We can see the updated info in the database as well:
Pic courtesy: medium.com
If you try to update a record that does not exist in the database you get 404 Not Found error:
Pic courtesy: medium.com
DELETE Method
Add the following code to the MoviesController:
Pic courtesy: medium.com
DeleteMovie method deletes the movie record with the given Id in the database. The preceding code is an HTTP DELETE method, as indicated by the [HttpDelete] attribute. This method expects Id in the URL to identify the movie record we want to delete.
Testing the DeleteMovie Method
Start the application and then select the DELETE method in the Movies section.
Click Try it out and enter the Id of the movie you want to delete in the id field:
Pic courtesy: medium.com
and then click Execute.
Pic courtesy: medium.com
We do not need to supply a request body as you might have noticed. The response status is 204 No Content.
If you try to get this movie record using the browser you get 404 Not Found error as expected:
Pic courtesy: medium.com
You can check as well from the database that the record is deleted:
Pic courtesy: medium.com
For more information and to develop a website using ASP.NET, Hire .NET Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”.
To develop a Website using ASP.NET, please visit our technology page.
Content Source:
- medium.com