使用jquery调用post web api方法

时间:2013-04-02 01:23:01

标签: jquery asp.net json web-services asp.net-web-api

我有一个像以下

这样的网络方法
    public HttpResponseMessage PostDeviceControl(DeviceAccessRequest deviceAccessRequest)
    {

        var deviceAccessResponse = new DeviceAccessResponse(deviceAccessRequest.RequestId)
            {
                Status = "OK"
            };
        var response = Request.CreateResponse<DeviceAccessResponse>(HttpStatusCode.OK, deviceAccessResponse);
        return response;
    }

这就是我从C#应用程序中消耗它的方式,它运行良好

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:55208/");

            var request = new DeviceAccessRequest
            {
                RequestId = Guid.NewGuid().ToString(),
                DeviceId = "ACU/B2/01/R1",
                AccessType ="Unlock",
                LoginId = "tester",
                Password = "tester" ,                    
            };
            var response = client.PostAsJsonAsync("api/accesspanel", request).Result;
            if (response.IsSuccessStatusCode)
            {
                var deviceAccessResponse = response.Content.ReadAsAsync<DeviceAccessResponse>().Result;

            }
        }

这是我的jquery片段

var request = {
    RequestId: "123",
    DeviceId: "ACU/B2/01/R1",
    AccessType: "Unlock",
    LoginId: "tester",
    Password: "tester"
};
alert(JSON.stringify(request));
$.ajax({
    url: 'http://localhost:55208/api/accesspanel',
    type: 'POST',
    data: JSON.stringify(request),
    contentType: "application/json;charset=utf-8",
    success: function (data) {
        alert(JSON.stringify(data));
    },
    error: function (x, y, z) {
        alert(x + '\n' + y + '\n' + z);
    }
});

我在我的web api方法中设置了断点,但它没有中断。并调用我的ajax()的错误部分。

我做错了什么?

0 个答案:

没有答案