国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

webapi的使用

2019-11-10 18:59:29
字體:
來源:轉載
供稿:網友

在Visual Studio 2012中新建MVC4項目,在App_Start目錄下有一個WebApiConfig.cs文件,這個文件中就是相應的Web API的路由配置了。

我也根據這兩篇文章寫了一個簡單的測試程序。

先創建了一個UserModel

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

然后添加Web API Controller

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

注冊路由

public static void Register(HttpConfiguration config){    config.Routes.MapHttPRoute(        name: "DefaultApi",        routeTemplate: "api/{controller}/{id}",        defaults: new { id = RouteParameter.Optional }    );}

在Global中注冊

protected void application_Start(object sender, EventArgs e){    WebApiConfig.Register(GlobalConfiguration.Configuration);}

這個時候用地址欄訪問地址:api/user/getadmin

這個時侯默認返回的是xml數據模型。

使用Ajax請求這個api,指定數據格式為json

$.ajax({    type: 'GET',    url: 'api/user/getadmin',    dataType: 'json',    success: function (data, textStatus) {        alert(data.UserID + " | " + data.UserName);    },    error: function (xmlhttpRequest, textStatus, errorThrown) {    }});

alert出來的結果是:

可以根據請求的數據類型返回指定的數據格式。

 

POST數據

修改一下controller,添加一個add方法

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

只為了測試,所以這里只判斷一下傳入的實體是否為空,如果不為空則返回true

我在頁面上添加了一個button,代碼如下:

<input type="button" name="btnOK" id="btnOK" value="發送POST請求" />

添加JS代碼

$('#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) {        }    });});

再次運行頁面


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 土默特左旗| 科技| 益阳市| 延长县| 金沙县| 且末县| 石景山区| 云和县| 建湖县| 桃园县| 宣威市| 平陆县| 济源市| 礼泉县| 柳林县| 南岸区| 邢台县| 延川县| 宁明县| 华容县| 溆浦县| 永城市| 北碚区| 安吉县| 友谊县| 阿拉善右旗| 天门市| 沙河市| 长岛县| 南木林县| 潮州市| 城市| 闽清县| 陕西省| 色达县| 丹江口市| 桦南县| 五寨县| 新邵县| 南开区| 桓台县|