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 , establish core webapi project , quote NuGet package :Install-Package
Microsoft.AspNetCore.Mvc.Versioning -Version 2.0.0



Project and installation package are ready , Then we need to Startup.cs In ConfigureServices Method to add the following code :



As you can see , Configured 3 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 is 1.0.
* DefaultApiVersion: This option specifies the default to use when no version is specified in the request API edition . This will default to 1.0.
This is all the configuration and settings . Now? , We will see the visit API Different ways of version .


Two , adopt QueryString To achieve version control

Turn on our controller , Add above ApiVersion characteristic , As shown in the following code :

The above code serves as 1.0 edition . You can also create another controller class with the same name in a different namespace , And will API Version set to 2.0 edition . As shown in the figure below :


That's it. . Now go to the browser and access the controller . You should see API edition 1.0 Controller output , Because it is set to the default value . Now in URL Middle append api-version=2,
You should see api edition 2.0 Controller output .

Two , adopt URL Path Segment To achieve :

Query string parameters are useful , But in the long run 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 be v1 and v2 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 , At visit API Version number is always required when interface . You can use api/v1/values Access to version 1.0,
adopt api/v2/values  Access version 2.0, change URL Version number in . simple , It looks cleaner .

The test results are as follows :

Three , adopt HTTP Headers To achieve version control

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




The highlighted lines tell us header  "api-version" Now it's 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 2.0 Supplied as value to "api edition " Time , It will call version 2.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 up header, The query string parameter cannot be specified . If you want to support both ,
instead of HeaderApiVersionReader, Please use QueryStringOrHeaderApiVersionReader. The code is as follows :


therefore , Query string parameters and are now supported header. 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 the figure 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 version 3 Supported 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 version 1.0 Medium support ,public string Getv3() Method only in version 3.0 Medium support .

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 , Just Deprecated
Decorate your controller . That doesn't mean no support API edition . You can still call this version . It's just a way of letting call API Users are aware that the following versions will be deprecated in the future .

The top Deprecated Set to TRUE express , edition 1.0 Will be abandoned in the future . Visit our API Interface , You can see it in the response header , The following information , As shown in the figure below :

ApiVersionNeutral Use of features :

ApiVersionNeutral Property defines this API Version control is not supported at . whether support api 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 a API Version control for , There is a way , No selling , Let's look down .


Four , The ultimate version ( Without any help NuGet package ) core web api version control

Create a new one core API project :


stay VersionControl Under folder , Create a new implementation
IApplicationModelConvention Class of interface NameSpaceVersionRoutingConvention    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 // obtain namespace 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 much @ Time splashed Point out my mistakes in time , Thank you very much !

Code download address :WebApiVersionControl.rar

author : Guo Zheng

source :

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 .