一、Web API的路由
1、在Visual Studio中新建MVC4項目,在App_Start目錄下有一個WebApiConfig.cs文件,這個文件中就是相應的Web API的路由配置了。
2、Web API 框架默認是基于 Restful 架構模式的,與ASP.NET MVC 有區別的是,它會根據 Http 請求的 HttpMethod(Get、Post、Put、Delete)來在Controller 中查找 Action,規則是:Action 名中是否以Get、Post 開頭?Action 上標記 HttpGet、HttpPost 等標記?
3、當然可以修改默認的配置,讓客戶端在調用時顯式指定 action 名稱,例如
1
2
3
4
5
|
config.Routes.MapHttpRoute( name: "DefaultApi" , routeTemplate: "api/{controller}/{action}/{id}" , defaults: new { id = RouteParameter.Optional } ); |
這樣,由于顯式指定了 Action 名稱,Web API 會使用該名稱來查找對應的 Action 方法,而不再按照 HttpMethod 約定來查找對應的 Action。
二、ASP.NET中Web API的簡單實例
1、Get請求數據
(1)、定義一個UserModel 類
1
2
3
4
5
|
public class UserModel { public string UserID { get ; set ; } public string UserName { get ; set ; } } |
(2)、添加一個Web API Controller :UserController
1
2
3
4
5
6
7
|
public class UserController : ApiController { public UserModel getAdmin() { return new UserModel() { UserID = "000" , UserName = "Admin" }; } } |
(3)、在瀏覽器訪問:api/user/getadmin (默認返回的是XML數據模型)
(4)、AJAX請求這個api,指定數據格式為json
1
2
3
4
5
6
7
8
9
10
|
$.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提交數據
(1)、UserController 里面添加一個Action
1
2
3
4
|
public bool add(UserModel user) { return user != null ; } |
(2)、頁面上添加一個button
1
|
< input type = "button" name = "btnOK" id = "btnOK" value = "發送POST請求" /> |
(3)、JS post提交數據
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
$( '#btnOK' ).bind( 'click' , function () { //創建ajax請求,將數據發送到后臺處理 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) { } }); }); |
以上就是ASP.NET中Web API的簡單實例,還包括Web API路由介紹,希望對大家的學習有所幫助。