I. Routing of the WEB API
1. Create a new MVC4 project in Visual Studio with a WebApiConfig.cs file in the App_start directory, which is the routing configuration of the corresponding Web API.
2. The Web API Framework is based on the default Restful schema pattern, and unlike ASP.net MVC, it looks for the httpmethod of the Http request (GET, Post, put, Delete) in controller to find action,< The c1> rule is: Does the Action name begin with a GET, Post? Mark HttpGet, HttpPost, etc. on Action?
3, of course, you can modify the default configuration, let the client explicitly specify the action name when called, for example
Config. Routes.maphttproute (
name: "Defaultapi",
routetemplate: "Api/{controller}/{action}/{id}",
defaults: New {id = routeparameter.optional}
);
Thus, because the action name is explicitly specified, the Web API uses that name to find the corresponding action method, instead of looking for the corresponding action according to the HttpMethod convention.
Second, ASP. Simple example of Web APIs in net
1. Get Request data
(1), define a Usermodel class
public class Usermodel
{public
string UserID {get; set;}
public string UserName {get; set;}
}
(2), add a Web API controller:usercontroller
public class Usercontroller:apicontroller
{public
Usermodel getadmin () {return
new Usermodel () { UserID = "N", UserName = "Admin"}
(3), in browser access: Api/user/getadmin (the default return is the XML data model)
(4), Ajax request This API, specify the data format for JSON
$.ajax ({
type: ' Get ',
URL: ' api/user/getadmin ',
dataType: ' json ',
success:function (data, Textstatus) {
alert (data. UserID + "|" + data. UserName);
},
error:function (XMLHttpRequest, Textstatus, Errorthrown) {
}
});
2, Post submission data
(1), Usercontroller inside add an action
Public boolean Add (Usermodel user)
{return
user!= null;
}
(2), add a button on the page
<input type= "button" Name= "Btnok" id= "Btnok" value= "send Post request"/>
(3), JS post submission data
$ (' #btnOK '). Bind (' click ', Function () {
//create AJAX request, send data to Background processing
var postdata = {
UserID: ' 001 ',
UserName: ' Qeefee '
};
$.ajax ({
type: ' POST ',
URL: ' Api/user/add ',
data:postdata,
dataType: ' JSON ',
success: function (data, textstatus) {
alert (data);
},
error:function (XMLHttpRequest, Textstatus, Errorthrown ) {
}
});
});
The above is a simple example of the Web API in ASP.net, but also includes the introduction of Web API routing, I hope to help you learn.