One, Benefits of versioning:

(1) Helps to roll out features in a timely manner, Without destroying the existing system.

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

API Version control can be controlled in different ways, The method is as follows:

(1) stay URL Append version in or as query string parameter,

(2) By customizing headers and by accepting headers

In this article, Let's see how to support multiple versions of ASP.NET  Core  Web API.

One, core webapi project, QuoteNuGet package:Install-Package
Microsoft.AspNetCore.Mvc.Versioning -Version 2.0.0



Project and installation package are ready, Then we need toStartup.cs MediumConfigureServices Method to add the following code:



As you can see, Configured3 Different options.

*  ReportAPIVersions: This is optional. however, When set to true Time, API The supported version information in the response header will be returned.
*  AssumeDefaultVersionWhenUnspecified: This option will be used for requests that do not provide a version. By default, Hypothetical API Version is1.0.
* DefaultApiVersion: This option specifies the default to use when no version is specified in the request API Edition. This will default to1.0.
This is all the configuration and settings. Now, We will see the visit API Different ways of version.


Two, adoptQueryString To achieve version control

Turn on our controller, Add aboveApiVersion Characteristic, As shown in the following code:

The above code serves as1.0 Edition. You can also create another controller class with the same name in a different namespace, And will API Version set to2.0 Edition. As shown in the figure below:


That's it.. Now go to the browser and access the controller. You should see API Edition1.0 Controller output, Because it is set to the default value. Now in URL Secondary addition api-version=2,
You should seeapi Edition2.0 Controller output.

Two, adoptURL Path Segment To achieve:

Query string parameters are useful, But in the long URL And other query string parameters can be painful. Contrary, The better way is to URL Add version in path. such as:

* api/v1/values
* api/v2/values
Or the above project, It just needs to bev1 andv2 Add to controller, The following code. As shown in the figure below:

same, You need to update the routing parameters to all applicable locations. Use this change, VisitAPI Version number is always required when interface. You can use api/v1/values Access to version 1.0,
adoptapi/v2/values  Access version 2.0, change URL Version number in. simple, It looks cleaner.

The test results are as follows:

Three, adoptHTTP Headers To achieve version control

In the above two methods, Need modification URL To support version control. however, If you wish api OfURL Keep clean, be api Version information can also be added by HTTP
The head of the newspaper. To do this, You need to configure ApiVersionReader option. The code is as follows:




The highlighted lines tell usheader  "api-version" Now is api Expected location of version number. Ensure that the routing properties do not have version details. So test it, give the result as follows:

When you will2.0 Supplied as value to "api Edition" Time, It will call version2.0 Controller and return to output.

simple, Easy to set up. however, Now the method of querying string parameters for version control will not work. Once set upheader, The query string parameter cannot be specified. If you want to support both,
Instead ofHeaderApiVersionReader, Please use QueryStringOrHeaderApiVersionReader. The code is as follows:


therefore, Query string parameters and are now supportedheader. The default query string parameter name is api-version, So you can leave the constructor empty, But if you need another name,
It is required to provide. You can also use different names for query string parameters and headers. please remember, We will also ReportApiVersions Set to true,
This value returns the version information in the response header. See below.


Now, Let's look at the other options.

MapToApiVersion Usage of parameters:

MapToApiVersion Property allows you to API Action mapped to any version. In other words, A single controller supporting multiple versions. Controller may only have version3 Supportive API
Operation method. under these circumstances, You can use the MapToApiVersion. Look at the code below.

The above code means:public string Get() This method is only available in version1.0 Support from China,public string Getv3() Method only in version3.0 Support from China.

There are pictures, there are real images, Very flexible, I like it so much.

Deprecated Usage of parameters:

When multiple API Version time, Some versions will eventually be discarded over time. To mark one or more api Version is obsolete, Need onlyDeprecated
Decorate your controller. That doesn't mean no support API Edition. You can still call this version. It's just a way of letting callAPI Users are aware that the following versions will be deprecated in the future.

Top handleDeprecated Set toTRUE Express, Edition1.0 Will be abandoned in the future. Visit ourAPI Interface, You can see it in the response header, Below information, As shown in the figure below:

ApiVersionNeutral Use of features:

ApiVersionNeutral Property defines this API Version control is not supported at. whether Supportapi Version control or not supported api Old style of version control api,
It's exactly the same for behavior api Very useful. therefore, You can add 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 do this with the following code:

In summary, With multiple versions of API Can help deliver enhanced features in an effective way, It's also easy to track changes. In this article, We saw how ASP.NET
 core WEB API Add support for multiple versions in.nuget Package supports version control by querying string parameters, stay URL Add path segments and pass through headers in. It also has a single version
API Operation and exit from version.

Can we implement aAPI Version control for, There is a way, No selling, Let's look down.


Four, Ultimate version( Without any helpNuGet package) core web api version control

Build a new one.core API project:


stayVersionControl Under folder, Create a new implementation
IApplicationModelConvention Class of interfacesNameSpaceVersionRoutingConvention    The code is as follows:

1 public class NameSpaceVersionRoutingConvention:IApplicationModelConvention
2 { 3 private readonly string apiPrefix; 4 private const string urlTemplate =
"{0}/{1}/{2}"; 5 public NameSpaceVersionRoutingConvention(string apiPrefix = "
api") 6 { 7 this.apiPrefix = apiPrefix; 8 } 9 10 public void
Apply(ApplicationModel application)11 { 12 foreach (var controller in
application.Controllers)13 { 14 15 var hasRouteAttribute = controller.Selectors
16 .Any(x => x.AttributeRouteModel != null); 17 if (!hasRouteAttribute) 18 { 19
continue; 20 } 21 var nameSpaces = controller.ControllerType.Namespace.Split('.
'); 22 // Obtainnamespace Medium version number part 23 var version = nameSpaces.FirstOrDefault(x =>
Regex.IsMatch(x,@"^v(\d+)$")); 24 if (string.IsNullOrEmpty(version)) 25 { 26
continue; 27 } 28 string template = string.Format(urlTemplate, apiPrefix,
version,29 controller.ControllerName); 30 controller.Selectors[0
].AttributeRouteModel =new AttributeRouteModel() 31 { 32 Template = template 33
};34 } 35 } 36 }

Debugging code finds that this method is only executed when the program runs for the first time, It will not be executed more than once, So it's very efficient.

Five, summary:

Through the implementation and comparison of the above two versions of control, I prefer third-party packages for versioning, This method is more powerful. It's all personal, You can decide which way to use according to different scenarios, All right, so far, Thank you, I hope it helps you.

If you think it's ok, Hope to recommend it~ Your recommendation is my motivation.


Thank you very [email protected] Time flies Point out my mistakes in time, Thank you very much.!

Code download address:WebApiVersionControl.rar

author: Guo Zheng


The copyright of this article belongs to the author and blog Park, Welcome to reprint, However, this statement must be retained without the consent of the author, And give the original link in the obvious position of the article page.