


Detailed comparison of several versions of WebApi in ASP.Net Core (picture)
This article mainly introduces a brief discussion of the comparison of several version controls of ASP.Net Core WebApi. The editor thinks it is quite good. Now I will share it with you and give you a reference. Let’s follow the editor and take a look.
1. Benefits of version control:
(1) It helps to launch functions in a timely manner, and Will not disrupt existing systems.
(2) It can also help provide additional features to selected customers.
API version control can be controlled in different ways, as follows:
(1) Append the version in the URL or as a query string parameter,
(2) By customizing headers and by accepting headers
In this post, let’s take a look at how to support multiple versions of ASP.NET Core Web API.
1. Create an asp.net core webapi project and reference the NuGet package: Install-Package Microsoft.AspNetCore.Mvc.Versioning -Version 2.0.0
The project and installation package are ready, then we need to add the following code to the ConfigureServices method in Startup.cs:
As you can see, there are 3 different options configured.
ReportAPIVersions: This is optional. However, when set to true, the API will return supported version information in the response header.
AssumeDefaultVersionWhenUnspecified: This option will be used for requests that do not provide a version. By default, the assumed API version is 1.0.
DefaultApiVersion: This option is used to specify the default API version to use when no version is specified in the request. This will default to version 1.0.
This is all the configuration and settings. Now, we will see the different ways to access API versions.
2. Implement version control through QueryString
Open our controller and add the ApiVersion feature on it, as shown in the following code:
The above code is version 1.0. You can also create another controller class with the same name in a different namespace and set the API version to version 2.0. As shown in the picture below:
That’s it. Now go to the browser and access the controller. You should see output from the API version 1.0 controller as it is set to the default. Now append api-version=2 in the URL and you should see the output of the api version 2.0 controller.
## 2. Implemented through URL Path Segment:
Query string parameters are useful, but can be a pain in the case of long URLs and other query string parameters. Instead, a better approach is to add the version in the URL path. For example:- api/v1/values
- api/v2/values
##3. Implement version control through HTTP HeadersIn the above two methods, the URL needs to be modified to support version control. However, if you want the API's URL to remain clean, the API version information can also be passed by appending an HTTP header. To make this work, you need to configure the ApiVersionReader options. code show as below:
The highlighted line tells us that the header "api-version" is now the expected location for the api version number. Make sure the route properties do not have version details. So tested it and here's the result:
When you provide 2.0 as a value to "api version", it will call the version 2.0 controller and return the output.
Simple and easy to set up. However, now the query string parameter method for versioning will not work. Once the header is set, query string parameters cannot be specified. If you want to support both cases, use QueryStringOrHeaderApiVersionReader instead of HeaderApiVersionReader. The code is as follows:
# Therefore, query string parameters and headers are now supported. The default query string parameter name is api-version, so you can leave the constructor empty, but if a different name is required, you need to provide it. You can also use different names for query string parameters and headers. Remember, we also set ReportApiVersions to true, which returns the version information in the response header. See below.
Now, let’s look at a few more options.
Usage of the MapToApiVersion parameter:
The MapToApiVersion property allows a single API operation to be mapped to any version. In other words, a single controller that supports multiple versions. Controllers may only have version 3 supported API action methods. In this case, you can use MapToApiVersion. Take a look at the code below.
The above code means: the public string Get() method is only supported in version 1.0, and the public string Getv3() method is only supported in version 3.0.
There are pictures and real images, it’s very flexible, I like it very much.
Usage of the Deprecated parameter:
When supporting multiple API versions, some versions will eventually be deprecated over time. To mark one or more API versions as deprecated, simply decorate your controller with Deprecated. This does not mean that API versions are not supported. You can still call that version. It is simply a way to make calling API users aware that the following versions will be deprecated in the future.
Setting Deprecated to TRUE above means that version 1.0 will be deprecated in the future. When accessing our API interface, you can see the following information in the response header, as shown in the figure below:
Usage of the ApiVersionNeutral feature:
ApiVersionNeutral Feature definition This API no longer supports versioning. This is useful for APIs that behave exactly the same regardless of whether they support API versioning or legacy APIs that don't support API versioning. Therefore, you can add the ApiVersionNeutral property to exit from version control.
Get version information (Version Information)
If you want to know which version of the client is being accessed, you can implement this function through the following code :
To sum up, having multiple versions of the API can help roll out enhanced functionality in an efficient way while also making it easier to track changes. In this article, we saw how to add support for multiple versions in the ASP.NET coreWEB API. The nuget package supports versioning via query string parameters, adding path segments in URLs and via headers. It also features version single API operations and the ability to opt out of versions.
Is it possible to implement version control of an API without resorting to third-party packages? There are methods. Let’s not get too carried away. Let’s read on.
4. Ultimate version (without any NuGet package) asp.net core web api version control
Create a new core API project:
Under the VersionControl folder, create a new class NameSpaceVersionRoutingConvention that implements the IApplicationModelConvention interface. The code is as follows:
public class NameSpaceVersionRoutingConvention:IApplicationModelConvention { private readonly string apiPrefix; private const string urlTemplate = "{0}/{1}/{2}"; public NameSpaceVersionRoutingConvention(string apiPrefix = "api") { this.apiPrefix = apiPrefix; } public void Apply(ApplicationModel application) { foreach (var controller in application.Controllers) { var hasRouteAttribute = controller.Selectors .Any(x => x.AttributeRouteModel != null); if (!hasRouteAttribute) { continue; } var nameSpaces = controller.ControllerType.Namespace.Split('.'); //获取namespace中版本号部分 var version = nameSpaces.FirstOrDefault(x => Regex.IsMatch(x, @"^v(\d+)$")); if (string.IsNullOrEmpty(version)) { continue; } string template = string.Format(urlTemplate, apiPrefix, version, controller.ControllerName); controller.Selectors[0].AttributeRouteModel = new AttributeRouteModel() { Template = template }; } } }
Debugging the code found this This method will only be executed when the program is run for the first time, and will not be executed multiple times after that, so it is very efficient.
5. Summary:
The above is the detailed content of Detailed comparison of several versions of WebApi in ASP.Net Core (picture). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Microsoft's Windows 11 2022 Update (22H2) enables CoreIsolation's memory integrity protection by default. However, if you are running an older version of the operating system, such as Windows 11 2022 Update (22H1), you will need to turn this feature on manually. Turn on CoreIsolation's Memory Integrity feature in Windows 11 For users who don't know about Core Isolation, it's a security process designed to protect basic core activities on Windows from malicious programs by isolating them in memory. This process, combined with the memory integrity feature, ensures

Core has two meanings in computers: 1. The core, also known as the core, is the most important component of the CPU. All calculations, accepting storage commands, and processing data of the CPU are performed by the core; 2. Core, core is Intel's processor Name, Core is the processor brand launched by Intel after the Pentium processor. It has currently released twelfth generation Core processors.
![How to Fix Processor Thermal Trip Error in Windows 11/10 [Fix]](https://img.php.cn/upload/article/000/000/164/168169038621890.png?x-oss-process=image/resize,m_fill,h_207,w_330)
Most of the devices, such as laptops and desktops, have been heavily used by young gamers and coders for a long time. The system sometimes hangs due to application overload. This forces users to shut down their systems. This mainly happens to players who install and play heavy games. When the system tries to boot after force shutdown, it throws an error on a black screen as shown below: Below are the warnings detected during this boot. These can be viewed in the settings on the event log page. Warning: Processor thermal trip. Press any key to continue. ..These types of warning messages are always thrown when the processor temperature of a desktop or laptop exceeds its threshold temperature. Listed below are the reasons why this happens on Windows systems. Many heavy applications are in

With the launch of .NETCore, .NET developers have a new opportunity to easily write and run .NET applications on multiple operating systems. This article will delve into how to use .NETCore to achieve cross-platform application development, and share best practice experience on operating systems such as Windows, Linux, and macOS. 1. Prepare the development environment. To start cross-platform application development, you first need to prepare the development environment for each target platform. Windows On Windows, you can install .NETCoreSDK through Visual Studio. After installation is complete, you can create and run .NETCore projects through Visual Studio. Li

CORE coin: Is it worth holding for the long term? CORE coin is a cryptocurrency based on the Proof of Work (PoW) consensus mechanism and was founded by the Core team in 2018. Its goal is to establish a secure, efficient, and scalable digital currency system that is widely used for payment and value storage. CORE coin is designed to provide a decentralized payment solution that provides users with more privacy protection and transaction convenience. Advantages and security of CORE currency: CORE currency is based on the workload proof consensus mechanism and has strong security. Efficient: CORE coin’s transaction speed is fast and can handle thousands of transactions per second. Scalable: CORE coin has a large block capacity and can support a large number of transactions. Decentralization: CORE coin is a decentralized cryptocurrency

Under Linux, core is a memory image with debugging information added. When a program exits or terminates abnormally under Linux, we will use the core file for analysis, which contains information such as memory, registers, stack pointers and other information when the program is running. The format is ELF, which can be understood as dumping the current status of the program into a file.

1. Introduction Since the project is separated from the front and back ends, the api interface and the web front end are deployed in different sites, so in the previous article, the webapiajax cross-domain request solution (cors implementation) uses cross-domain processing instead of jsonp. But after a period of time, I discovered a very strange problem. Every time the front end initiates a request, through the browser's developer tools, I can see that there are two requests for the same URL under the network. The method of the first request is options, the method of the second request is the real get or post, and the first request returns no data, and the second request returns normal data. 2. Reason for the first options

Roughly one year after announcing the Core Ultra Series 1, also known as Meteor Lake, Intel follows up with the second generation. Core Ultra Series 2 aka Lunar Lake was already introduced at June's Computex. At IFA, the final launch of the Core Ultr
