欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

ASP.NET中Web API的簡(jiǎn)單實(shí)例

 更新時(shí)間:2015年10月29日 14:24:13   投稿:lijiao  
Web API框架是一個(gè)面向Http協(xié)議的通信框架,Web API 框架是一個(gè)面向Http協(xié)議的通信框架。Web API 框架目前支持兩種數(shù)據(jù)格式的序列化:Json 及 Xml。在不做任何配置的情況下,則 Web API 會(huì)自動(dòng)把數(shù)據(jù)使用xml進(jìn)行序列化,否則使用 json 序列化,需要的朋友可以參考下

一、Web API的路由
1、在Visual Studio中新建MVC4項(xiàng)目,在App_Start目錄下有一個(gè)WebApiConfig.cs文件,這個(gè)文件中就是相應(yīng)的Web API的路由配置了。
2、Web API 框架默認(rèn)是基于 Restful 架構(gòu)模式的,與ASP.NET MVC 有區(qū)別的是,它會(huì)根據(jù) Http 請(qǐng)求的 HttpMethod(Get、Post、Put、Delete)來(lái)在Controller 中查找 Action,規(guī)則是:Action 名中是否以Get、Post 開(kāi)頭?Action 上標(biāo)記 HttpGet、HttpPost 等標(biāo)記?
3、當(dāng)然可以修改默認(rèn)的配置,讓客戶端在調(diào)用時(shí)顯式指定 action 名稱,例如

config.Routes.MapHttpRoute(
 name: "DefaultApi",
 routeTemplate: "api/{controller}/{action}/{id}",
 defaults: new { id = RouteParameter.Optional }
);

這樣,由于顯式指定了 Action 名稱,Web API 會(huì)使用該名稱來(lái)查找對(duì)應(yīng)的 Action 方法,而不再按照 HttpMethod 約定來(lái)查找對(duì)應(yīng)的 Action。
 二、ASP.NET中Web API的簡(jiǎn)單實(shí)例
 1、Get請(qǐng)求數(shù)據(jù)
(1)、定義一個(gè)UserModel 類

public class UserModel
{
 public string UserID { get; set; }
 public string UserName { get; set; }
}

(2)、添加一個(gè)Web API Controller :UserController

public class UserController : ApiController
{
 public UserModel getAdmin()
 {
  return new UserModel() { UserID = "000", UserName = "Admin" };
 } 
}

(3)、在瀏覽器訪問(wèn):api/user/getadmin (默認(rèn)返回的是XML數(shù)據(jù)模型)

(4)、AJAX請(qǐng)求這個(gè)api,指定數(shù)據(jù)格式為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提交數(shù)據(jù)
(1)、UserController 里面添加一個(gè)Action

public bool add(UserModel user)
{
 return user != null;
}

(2)、頁(yè)面上添加一個(gè)button

<input type="button" name="btnOK" id="btnOK" value="發(fā)送POST請(qǐng)求" />

(3)、JS post提交數(shù)據(jù)

$('#btnOK').bind('click', function () {
 //創(chuàng)建ajax請(qǐng)求,將數(shù)據(jù)發(fā)送到后臺(tái)處理
 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的簡(jiǎn)單實(shí)例,還包括Web API路由介紹,希望對(duì)大家的學(xué)習(xí)有所幫助。

相關(guān)文章

最新評(píng)論