1. 程式人生 > >探秘如何操作 ASP.NET Web API (三)

探秘如何操作 ASP.NET Web API (三)

asp ajax請求 log pic margin div 判斷 out turn

經過我三篇文章的解惑,webapi我相信大家沒有問題了!

先創建了一個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出來的結果是:

技術分享

這樣看來,真的是dudu所說的,可以根據請求的數據類型返回指定的數據格式。

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) {
        }
    });
});

再次運行頁面

技術分享

我們附加進程進行調試,在發送ajax請求的時候,服務器段接收到的數據如圖:

技術分享

如果認為此文對您有幫助,別忘了支持一下哦!

作者:齊飛 來源:http://youring2.cnblogs.com/

探秘如何操作 ASP.NET Web API (三)