Simple Example of Web API in ASP. NET, asp. netapi
1. Web API Routing
1. Create an MVC4 project in Visual Studio. There is a WebApiConfig. cs file under the App_Start Directory, which contains the routing configuration of the corresponding Web API.
2. The Web API framework is based on the Restful architecture by default. the difference between. net mvc is that it searches for Action in the Controller Based on the Http method (Get, Post, Put, Delete) of the Http request,RulesYes: Does the Action name start with Get or Post? Mark HttpGet and HttpPost on Action?
3. Of course, you can modify the default configuration so that the client explicitly specifies the action name during the call, for example
config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional });
In this way, because the Action name is explicitly specified, the Web API uses this name to find the corresponding Action method, instead of looking for the corresponding Action according to the HttpMethod convention.
Ii. Simple examples of Web APIs in ASP. 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 = "000", UserName = "Admin" }; } }
(3) access in a browser: api/user/getadmin (the XML data model is returned by default)
(4) AJAX requests this api and specifies the data format as 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. submit data through POST
(1) Add an Action in UserController
public bool 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) submit data through JS post
$ ('# Btnok '). bind ('click', function () {// create an ajax request and send the data to the backend for processing var postData = {UserID: '001', UserName: 'qeeket'}; $. ajax ({type: 'post', url: 'api/user/add', data: postData, ype: 'json', success: function (data, textStatus) {alert (data) ;}, error: function (xmlHttpRequest, textStatus, errorThrown ){}});});
The above is a simple example of Web API in ASP. NET. It also includes Web API routing introduction, hoping to help you learn.