In the ASP. NET Web API, when our API changes, it involves version issues. How to implement the API version?
1. Set the version via routing
The simplest way is through routing settings, different routes, different versions, different controllers.
CONFIG. Routes.maphttproute ( "food", "api/v1/nutrition/ Foods/{foodid}", defaults: ...) Config. Routes.maphttproute ( "Foodv2", " Api/v2/nutrition/foods/{foodid}", defaults: ...)
2, through the Httpcontrollerselector
This can also be achieved by changing the httpcontrollerselector.
First write a class that inherits Defaulthttpcontrollerselector.
usingSystem.Web.http.Dispatcher Public classcountingkscontrollerselector:defaulthttpcontrollerselector{Privatehttpconfiguraion _config; PublicCountgkscontrollerselector (Httpconfiguraiton cofig):Base(config) {_config=config; } //design is the process of returning to Httpcontrollerdesriptor Public OverrideSystem.Web.Http.Controllers.HttpControllerDescriptor Selectcontroller (httprequestmessage request) {//gets all the controller key value collections varcontrollers =getcontrollermapping (); //Get Route data varRoutedata =request. Getroutedata (); //gets the name of the current controller from the route varControllername = (string) routedata.values["Controller"]; Httpcontrollerdescriptor descriptor; if(controllers. TryGetValue (Controllername, outdescriptor)) { varVersion ="2"; //get version from QueryString varNewName =string. Concat (Controllername,"V", version); Httpcontrollerdescriptor Versioneddescriptor; if(controllers. TryGetValue (NewName, outversioneddescriptor)) { returnVersioneddescriptor; } returndescriptor; } return NULL; }}
Register your custom Controllerselector in WebApiConfig.cs
Config. Services.replace (typeofnew countingkscontrollerselector (config));
The above is a general idea of implementation. Specifically, this can be done in several ways.
Implementing versions with query string
The client roughly requests this:
http://localhost:8901/api/nutrition/foods/4492/measures/7269?v=2
usingSystem.Web.http.Dispatcher Public classcountingkscontrollerselector:defaulthttpcontrollerselector{Privatehttpconfiguraion _config; PublicCountgkscontrollerselector (Httpconfiguraiton cofig):Base(config) {_config=config; } //design is the process of returning to Httpcontrollerdesriptor Public OverrideSystem.Web.Http.Controllers.HttpControllerDescriptor Selectcontroller (httprequestmessage request) {//gets all the controller key value collections varcontrollers =getcontrollermapping (); //Get Route data varRoutedata =request. Getroutedata (); //gets the name of the current controller from the route varControllername = (string) routedata.values["Controller"]; Httpcontrollerdescriptor descriptor; if(controllers. TryGetValue (Controllername, outdescriptor)) { //var version = "2"; //get version from QueryString varVersion =getversionfromquerystring (Request); varNewName =string. Concat (Controllername,"V", version); Httpcontrollerdescriptor Versioneddescriptor; if(controllers. TryGetValue (NewName, outversioneddescriptor)) { returnVersioneddescriptor; } returndescriptor; } return NULL; } //get version from QueryString Private stringgetversionfromquerystring (Httprequestmessage request) {varquery =httputility.parsequerystring (Request. Requesturi.query); varVersion = query["v"]; if(Version! =NULL) { returnversion; } return "1"; }}
Implementing versions with headers
The client roughly requests this:
User-agent:fiddler
host:locahohost:8901
X-countingks-version:2
Private stringGetversionfromheader (Httprequestmessage request) {Const stringHeader_name ="x-countingks-version"; if(Request. Headers.contains (Header_name)) {varHeader =request. Headers.getvalues (Header_name). FirstOrDefault (); if(Header! =NULL) { returnheader; } } return "1";}
Implementing versions with Accept-header
The client roughly requests this:
User-agent:fiddler
host:locahohost:8901
accept:application/json;version=2
Private stringgetversionfromacceptheaderversion (Httprequestmessage request) {varAccept =request. headers.accept; foreach(varMimeinchaccept) { if(MIME. mediatype = ="Applicaiton/json") { varValue =MIME. Parameters. Where (v= V.name.equals ("version", Stringcomparison.ordinalingorecase)) . FirstOrDefault (); returnvalue. Value; } } return "1"; }
Implementing versions with mediatype
In the WebApiConfig.cs
varJsonformatter = config. Formatters.oftype<jsonmediatypeformatter>(). FirstOrDefault (); JsonFormatter.SerializerSettings.ContractResolver=NewCamelcasepropertynamescontractresolver (); Createmediatypes (jsonformatter);Private Static voidcreatemediatypes (Jsonmediatypeformatter jsonformatter) {varMediaTypes =New string[] { "Application/vnd.counting,s.food.v1+json", "Application/vnd.countingks.measure.v1+json", "Application/vnd.countgks.measure.v2+json", "Applicatikon/vnd.countingks.diary.v1+json", "Application/vnd.countingks.diaryentry.v1+json" }; foreach(varMediaTypeinchmediatypes) {JSONFORMATTER.SUPPORTEDMEIDATYPES.ADD (NewMediatypeheadervalue (mediatype)); }}
In the client roughly such a request:
User-agent:fiddler
host:localhost:8901
Accept:application/vnd.countingks.food.v1+json
Private stringGetversonfrommediatype (Httprequestmessage request) {varAccept =request. headers.accept; varex =NewRegex (@"application\/vnd\.countingks\. ([a-z]+) \.v ([0-9]+) \+json". Regexoptions.ignorecase); foreach(varMimeinchaccept) { varMatch =Ex. Match (MIME. mediatype); if(Match! =NULL) { returnMatch. groups[2]. Value; } } return "1";}
Using SDammann.WebApi.Versioning
Https://github.com/Sebazzz/SDammann.WebApi.Versioning
Several ways to implement versions in the ASP. NET Web API