ASP. NET Web API implements several versions, asp. netapi

Source: Internet
Author: User

ASP. NET Web API implements several versions, asp. netapi

 

In ASP. NET Web APIs, when our APIs change, the version issue is involved. How to Implement the API version?

 

1. Set the version through routing

 

The simplest way is to set routes, different routes, different versions, and different controllers.

 

config.Routes.MapHttpRoute(    name: "Food",    routeTemplate: "api/v1/nutrition/foods/{foodid}",    defaults:...)config.Routes.MapHttpRoute(    name: "Foodv2",    routeTemplate: "api/v2/nutrition/foods/{foodid}",    defaults:...)

 

2. Use HttpControllerSelector

 

You can also change HttpControllerSelector.

 

First, write a class that inherits DefaultHttpControllerSelector.

 

Using System. web. http. dispatcherpublic class CountingKsControllerSelector: DefaultHttpControllerSelector {private http%aion _ config; public CountgKsControllerSelector (http%aiton cofig): base (config) {_ config = config ;} // The design is the process of returning HttpControllerDesriptor public override System. web. http. controllers. httpControllerDescriptor SelectController (HttpRequestMessage request) {// obtain all the controller key value sets var controllers = GetControllerMapping (); // obtain route data var routeData = request. getRouteData (); // obtain the name of the current controller from the route var controllerName = (string) routeData. values ["controller"]; HttpControllerDescriptor descriptor; if (controllers. tryGetValue (controllerName, out descriptor) {var version = "2"; // obtain the var newName = string from QueryString. concat (controllerName, "V", version); HttpControllerDescriptor versionedDescriptor; if (controllers. tryGetValue (newName, out versionedDescriptor) {return versionedDescriptor;} return descriptor;} return null ;}}

 

Register the custom ControllerSelector in WebApiConfig. cs

 

config.Services.Replace(typeof(IHttpControllerSelector), new CountingKsControllerSelector(config) );

 

The above is a general idea of implementation. Specifically, you can use the following methods.

 

■ Implement version through Query String

The client requests roughly like this:

Http: // localhost: 8901/api/nutrition/foods/4492/measures/7269? V = 2

 

Using System. web. http. dispatcherpublic class CountingKsControllerSelector: DefaultHttpControllerSelector {private http%aion _ config; public CountgKsControllerSelector (http%aiton cofig): base (config) {_ config = config ;} // The design is the process of returning HttpControllerDesriptor public override System. web. http. controllers. httpControllerDescriptor SelectController (HttpRequestMessage request) {// obtain all contro Roller key value set var controllers = GetControllerMapping (); // obtain route data var routeData = request. getRouteData (); // obtain the name of the current controller from the route var controllerName = (string) routeData. values ["controller"]; HttpControllerDescriptor descriptor; if (controllers. tryGetValue (controllerName, out descriptor) {// var version = "2"; // obtain the var version = GetVersionFromQueryString (request) from QueryString; var newName = string. conc At (controllerName, "V", version); HttpControllerDescriptor versionedDescriptor; if (controllers. tryGetValue (newName, out versionedDescriptor) {return versionedDescriptor;} return descriptor;} return null;} // obtain the private string GetVersionFromQueryString (HttpRequestMessage request) from QueryString) {var query = HttpUtility. parseQueryString (request. requestUri. query); var version = query ["v"]; if (ve Rsion! = Null) {return version;} return "1 ";}}

 

■ Implement version through Header

The client requests roughly like this:

User-Agent: Fiddler
Host: locahohost: 8901
X-CountingKs-Version: 2

 

private string GetVersionFromHeader(HttpRequestMessage request){    const string HEADER_NAME = "X-CountingKs-Version";        if(request.Headers.Contains(HEADER_NAME))    {        var header = request.Headers.GetValues(HEADER_NAME).FirstOrDefault();                if(header != null)        {            return header;        }    }    return "1";}

 

■ Implement version through Accept-Header

The client requests roughly like this:

User-Agent: Fiddler
Host: locahohost: 8901
Accept: application/json; version = 2

 

private string GetVersionFromAcceptHeaderVersion(HttpRequestMessage request){    var accept = request.Headers.Accept;        foreach(var mime in accept)    {        if(mime.MediaType == "applicaiton/json")        {            var value = mime.Parameters                .Where(v => v.Name.Equals("version",StringComparison.OrdinalIngoreCase))                .FirstOrDefault();                        return value.Value;        }    }        return "1";    }

 

■ Implement version through MediaType

In WebApiConfig. cs

 

var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().FirstOrDefault();jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();CreateMediaTypes(jsonFormatter);private static void CreateMediaTypes(JsonMediaTypeFormatter jsonFormatter){    var mediaTypes = 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(var mediaType in mediaTypes)    {        jsonFormatter.SupportedMeidaTypes.Add(new MediaTypeHeaderValue(mediaType));    }}

 

In the client, the request is roughly as follows:

User-Agent: Fiddler
Host: localhost: 8901
Accept: application/vnd. countingks. food. v1 + json

 

private string GetVersonFromMediaType(HttpRequestMessage request){    var accept = request.Headers.Accept;    var ex = new Regex(@"application\/vnd\.countingks\.([a-z]+)\.v([0-9]+)\+json". RegexOptions.IgnoreCase);        foreach(var mime in accept)    {        var match = ex.Match(mime.MediaType);        if(match != null)        {            return match.Groups[2].Value;        }    }    return "1";}

 


■ Use SDammann. WebApi. Versioning

Https://github.com/Sebazzz/SDammann.WebApi.Versioning

 

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.