parameters, multiple versions, and filter for Web APIs

Source: Internet
Author: User

First, about the parameters of the API
A) The Web API has a route template configured in WebApiConfig.cs, the default is "Api/{controller}/{id}", which differs from the MVC routing template in that there is no {action}, and the corresponding method is found according to the request. Whenever an action is labeled [HttpGet], the GET request is routed to the action regardless of the name of the action.
b) If a GET request is http:/***/api/controller?user= "U1" &pwd= "P1", according to the default routing configuration, a valid get method can be public string Login (string user, string pwd). You can also use [Fromuri], but the get method changes to public string Login ([Fromuri]loginmodel model), encapsulates the parameter as model and adds Fromuri,fromuri can only label one parameter, It is also possible to use multiple parameters while using Fromuri.
c) for a post, put request, can also be written as a GET request in the URI, but the parameters of the time is best to encapsulate, passing through the request body, while the parameters are labeled [Frombody]. The same token can only be used once. For the Post method public string Login2 (int i,[frombody]loginmodel model,string US), the request is in the order of the I and US parameters passed in the URL.
D) can also mimic the MVC route template, configured as "Api/{controller}/{action}/{id}", so that the use of more intuitive, but not based on the request to automatically correspond, and do not conform to the rest style.
Multi-version management of WEBAPI
Sometimes you need to keep an older version of the API while upgrading the API, and different URLs request different versions of the API. At this point, you can deploy different versions of the API on different servers or domain names. Or put it in the same project, and then use Ihttpcontrollerselector to differentiate between the different versions, the code is as follows:
public class Versioncontrollerselector:defaulthttpcontrollerselector {
Private Httpconfiguration _config;
Public Versioncontrollerselector (httpconfiguration configuration): Base (configuration) {
_config = Configuration;
}
public override Idictionary<string, Httpcontrollerdescriptor> getcontrollermapping () {
dictionary<string, httpcontrollerdescriptor> dict = new dictionary<string, httpcontrollerdescriptor> ();
foreach (Var asm in _config. Services.getassembliesresolver (). Getassemblies ()) {
Get all non-abstract classes that inherit from Apicontroller
var controllertypes = asm. GetTypes (). Where (t =!t.isabstract && typeof (Apicontroller). IsAssignableFrom (t)). ToArray ();
foreach (Var ctrltype in controllertypes) {
Extract the version number from the namespace
var match = Regex.match (Ctrltype.namespace, @ "_8._1_WEBAPI.CONTROLLERS.V (\d+)");
if (match. Success) {
String vernum = match. GROUPS[1]. Value;
String ctrlname = Regex.match (Ctrltype.name, "(. +) Controller"). GROUPS[1]. Value;
String key = Ctrlname + "V" + vernum;
Dict[key] = new Httpcontrollerdescriptor (_config, Ctrlname, Ctrltype);
}
}
}
return dict;
}

public override Httpcontrollerdescriptor Selectcontroller (Httprequestmessage request) {

var controllers = getcontrollermapping ();
Get Route data
var routedata = Request. Getroutedata ();
Gets the name of the current controller from the route
var controllername = (string) routedata.values["Controller";
Get the version number from the URL
String vernum = Regex.match (Request. Requesturi.pathandquery, @ "api/v (\d+)"). GROUPS[1]. Value;
Get version number from message header
String vernum = Request. Headers.getvalues ("Apiversion"). Single ();
String key = Controllername + "V" + vernum;
return controllers. ContainsKey (key)? Controllers[key]: null;
}
}

Then configure the two route templates in Webapiconfig:
Config. Routes.maphttproute (
Name: "DefaultApiv1",
Routetemplate: "Api/v1/{controller}/{id}",
defaults:new {id = routeparameter.optional}
);

Config. Routes.maphttproute (
Name: "DefaultApiv2",
Routetemplate: "Api/v2/{controller}/{id}",
defaults:new {id = routeparameter.optional}

Finally, replace the ihttpcontrollerselector with the versioncontrollerselector that you have written.
Config. Services.replace (typeof (Ihttpcontrollerselector), new Versioncontrollerselector (config));

Third, Filter
The syntax of the filter is similar to that of MVC, and it works in the same line, providing AOP functionality. But they were written directly in the form of asynchrony.
A) basic use of Iauthorizationfilter
public class Myauthfilter:iauthorizationfilter {
public bool AllowMultiple = true;

Public async taskIenumerable<string> values;
if (ActionContext.Request.Headers.TryGetValues ("UserName", out values)) {
var userName = values. FirstOrDefault ();
if (!username.equals ("admin")) {
return new Httpresponsemessage (httpstatuscode.unauthorized);
}
}
else {
return new Httpresponsemessage (httpstatuscode.unauthorized);
}
return await continuation ();
}
}
b) basic use of Iexceptionfilter
public class Exceptionfilter:iexceptionfilter {
public bool AllowMultiple = FALSE;

Public async Task Executeexceptionfilterasync (Httpactionexecutedcontext actionexecutedcontext, CancellationToken CancellationToken) {
using (StreamWriter writer = File.appendtext ("D:/err.txt")) {
await writer. Writelineasync (ActionExecutedContext.Exception.ToString ());
}
}
}


Learning materials: such as Peng Net. NET Accelerated http://www.rupeng.com/News/10/4603.shtml

parameters, multiple versions, and filter for Web APIs

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.