A comparison of several versioning controls in ASP. NET Core for Webapi

Source: Internet
Author: User
This article mainly introduces the introduction of several versions of the ASP. NET Core Webapi version control comparison, small series feel very good, and now share to everyone, but also for everyone to do a reference. Let's take a look at it with a little knitting.

One, version control benefits:

(1) facilitates the timely introduction of functions without destroying existing systems.

(2) It can also help provide additional functionality for selected customers.

API versioning can be controlled in a variety of ways, as follows:

(1) Append the version to the URL or as a query string parameter,

(2) through the custom header and by accepting the header

In this article, let's look at how to support multiple versions of the ASP. NET Core Web API.

First, create an ASP. Webapi project that references the NuGet package: Install-package microsoft.aspnetcore.mvc.versioning-version 2.0.0

The project and the installation package are good, and then we need to add the following code to the Configureservices method in Startup.cs:

As you can see, 3 different options are configured.

    • Reportapiversions: This is optional. However, when set to True, the API returns the version information that is supported in the response header.

    • Assumedefaultversionwhenunspecified: This option will be used for requests that do not provide a version. By default, the API version is assumed to be 1.0.

    • Defaultapiversion: This option specifies the default API version to use when a version is not specified in the request. This will be the default version of 1.0.

This is all the configuration and settings. Now, we'll see different ways to access the API version.

Second, through the querystring to achieve version control

Open our controller and add the Apiversion feature above, as shown in the following code:

The above code acts as 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 following:

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 the api-version=2 to the URL, you should see the output of the API version 2.0 controller.

Second, through the URL Path segment to achieve:

Query string parameters are useful, but can be painful in the case of long URLs and other query string parameters. Instead, a better approach is to add a version to the URL path. Like what:

    • Api/v1/values

    • Api/v2/values

Or the above project, just need to add in the V1 and V2 controller, the following code. As shown in the following:

Again, you need to update the routing parameters to all applicable locations. With this change, the version number is always required to access the API interface. You can change the version number in the URL by Api/v1/values access to version 1.0 through Api/v2/values access to version 2.0. It's simple, it looks cleaner.

The test results are as follows:

Third, using HTTP headers to achieve version control

In both of these methods, you need to modify the URL to support version control. However, if you want the URL of the API to remain clean, the API version information can also be passed by attaching an HTTP header. To do this, you need to configure the Apiversionreader option. The code is as follows:

The highlighted line tells us that the header "Api-version" is now the expected location for the API version number. Ensure that the routing properties do not have version details. So test it, the results are as follows:

When you supply 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 up. However, the method of querying string parameters now has no effect on versioning. Once the header is set, you cannot specify a query string parameter. If you want to support both cases instead of headerapiversionreader, use Querystringorheaderapiversionreader. 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 blank, but you need to provide it if you need a different name. You can also use different names for query string parameters and headers. Keep in mind that we also set Reportapiversions to True, which returns the version information in the response header. See.

Now, let's take a look at a few other options.

Use 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. The controller may have only version 3 supported API action methods. In this case, you can use Maptoapiversion. Look at the code below.

The above code means: public string Get () This method is supported only in version 1.0, and the public string GETV3 () method is only supported in version 3.0.

There is a picture of true, very flexible, I like it.

Use of the deprecated parameter:

When multiple API versions are supported, some versions end up being deprecated over time. To flag one or more API versions that have been deprecated, simply decorate your controller with deprecated. This does not mean that the API version is not supported. You can still call this version. It is just a way for the calling API user to realize that the following versions will be deprecated in the future.

Setting deprecated to True indicates that version 1.0 will be deprecated in the future. Access our API interface, which can be seen in the response header, as shown in the following information:

Use of Apiversionneutral features:

apiversionneutral attribute definition This API is not supported for versioning. This is useful for APIs that behave identically, regardless of the legacy API that supports API versioning or does not support API versioning. Therefore, you can add the Apiversionneutral property to exit from version control.

Get version information (information)

If you want to know which version of the client is being accessed, you can do that with the following code:

In summary, having multiple versions of the API can help to roll out enhanced functionality in an efficient way, while also making it easier to track changes. In this article, we see how to add support for multiple versions in the ASP. NET Coreweb API. The NuGet package supports versioning by querying string parameters, adding path segments and passing headers in URLs. It also features version single API operations and the ability to opt out from the release.

Can not use a third-party package to implement a version of the API control, the method is some, not suspense, everyone went on to look down.

Iv. 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 code that implements the Iapplicationmodelconvention interface 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; The public void is 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 ('. ');        Get namespace part of version number 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 code finds that this is done only when the program is first run and is not executed more than once, making it highly efficient.

Five, Summary:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.