Comparison of several versions of ASP. Net Core WebApi and asp. netwebapi
I. Benefits of Version Control:
(1) facilitate timely release of functions without disrupting the existing system.
(2) It can also help provide additional features for selected customers.
API version control can be implemented in different ways. The method is as follows:
(1) append a version to a URL or use it as a query string parameter,
(2) Use custom headers and accept Headers
In this article, let's take a look at how to support multiple versions of ASP. NET Core Web APIs.
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 the installation package are ready. Then we need to add the following code in the ConfigureServices method of Startup. cs:
As you can see, three different options are configured.
- ReportAPIVersions: This is optional. However, if it is set to true, the API returns the version information supported in the response header.
- Assumedefaverversionwhenunspecified: This option is used for requests that do not provide a version. By default, the API version is assumed to be 1.0.
- DefaultApiVersion: This option is used to specify the default API version to be used when no version is specified in the request. The default version is 1.0.
This is all configurations and settings. Now we will see different ways to access the API version.
Ii. Implement version control through QueryString
Open our controller and add the ApiVersion feature above, as shown in the following code:
The above code is used as Version 1.0. You can also create another controller class with the same name in different namespaces and set the API version to version 2.0. As shown in:
That's it. Now go to the browser and access the controller. You should see the output of the API version 1.0 Controller because it is set to the default value. Now append api-version = 2 to the URL. You should see the output of api version 2.0 controller.
2. Implemented through URL Path Segment:
It is useful to query string parameters, but it may be painful to query long URLs and other string parameters. On the contrary, it is better to add a version in the URL path. For example:
- Api/v1/values
- Api/v2/values
Or the above project, but the following code needs to be added to the v1 and v2 controllers. As shown in:
Similarly, you must update the route parameters to all applicable locations. With this change, a version number is always required to access the API. You can access version 1.0 through api/v1/values and Access Version 2.0 through api/v2/values to change the version number in the URL. Simple and looks cleaner.
The test results are as follows:
3. Version Control through HTTP Headers
In the preceding two methods, you must modify the URL to support version control. However, if you want to keep the api URL clean, the api version information can also be transmitted by appending an HTTP header. To do this, you must configure the ApiVersionReader option. The Code is as follows:
The highlighted line tells us that header "api-version" is the expected position of the api version number. Make sure that the route attributes do not have version details. So test it and the result is as follows:
When you provide 2.0 as a value to the api version, it calls the version 2.0 controller and returns the output.
Simple and Easy to set. However, the current method for querying string parameters for version control does not work. Once the header is set, the query string parameter cannot be specified. If you want to support these two cases, instead of HeaderApiVersionReader, use QueryStringOrHeaderApiVersionReader. The Code is as follows:
Therefore, string parameters and headers can be queried. The default query string parameter name is api-version, so you can leave the constructor empty, but if you need other names, you need to provide. You can also use different names for query string parameters and headers. Remember, we also set ReportApiVersions to true. This value returns the version information in the response header. See.
Now let's take a look at several other options.
MapToApiVersion usage:
The MapToApiVersion attribute allows you to map a single API operation to any version. In other words, a single controller that supports multiple versions. The Controller may only have API operations supported by version 3. In this case, you can use MapToApiVersion. Take a look at the following code.
The code above indicates that 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.
I like it very much.
Deprecated usage:
When multiple API versions are supported, some versions will be discarded over time. To mark that one or more api versions have been Deprecated, use Deprecated to modify your controller. This does not mean that the API version is not supported. You can still call this version. It is only a way for API users to realize that the following versions will be discarded in the future.
If Deprecated is set to TRUE, version 1.0 will be discarded in the future. You can see the following information in the response header when accessing our API interface, as shown in:
Use of ApiVersionNeutral features:
The ApiVersionNeutral feature defines that this API does not support version control. Whether it supports api version control or legacy APIs that do not support api version control, this is useful for APIs with identical behavior. Therefore, you can add the ApiVersionNeutral attribute to exit from version control.
Get Version Information)
If you want to know that the client version is being accessed, you can use the following code to implement this function:
To sum up, APIs with multiple versions can help to provide enhanced functions in an effective way and facilitate tracking changes. In this article, we see how to add support for multiple versions in ASP. NET coreWEB API. The nuget package supports version control by querying string parameters, adding path segments and passing headers to URLs. It also provides a single version of API operations and the function of selecting to exit from the version.
You can use a third-party package to implement Version Control for an API. There are some methods and you don't want to sell them out. Let's take a look.
Iv. Ultimate version (without any NuGet package) asp.net core web api Version Control
Create a core API project:
In the VersionControl folder, create a NameSpaceVersionRoutingConvention class that implements the IApplicationModelConvention interface. The Code is as follows:
Public class Expiration: 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. S Electors. Any (x => x. AttributeRouteModel! = Null); if (! HasRouteAttribute) {continue;} var nameSpaces = controller. controllerType. namespace. split ('. '); // obtain the var version = nameSpaces in namespace. 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 };}}}
Code debugging finds that this method is only executed when the program is run for the first time, and will not be executed multiple times later, so the efficiency is very high.
V. Summary:
Through the implementation and comparison of the above two types of version control, I prefer to use a third-party package to implement version control. This method is more powerful. This is a personal hobby. You can decide which method to use based on different scenarios. Let's talk about it. Thank you. I hope it will help you. We also hope that you can support the customer's home.