【发布时间】:2015-05-12 17:26:14
【问题描述】:
在开发真正的应用程序之前,我正在对 Web Api 项目进行小测试。我实现了一些基本的GET 操作没有问题,但是POST 请求存在一些问题。
我用这样的jQuery调用POST请求
var data = { name: "Pedro" };
$.post({
url: "http://localhost/Demo/api/user",
dataType: "json",
contentType: "application/json;charset=utf-8",
data: $.stringify("="+data),
success: function (data) {
alert(data[0].Name);
},
error: function () {
alert("error");
},
complete: function () {
alert("complete");
}
})
我的 POST 操作是这样的(在 UserController.vb 上)
Public Function PostUser(<FromBody()> ByVal name As String) As Demo.User.Model.User
Dim ids As Integer() = From userId In (From user In users Select user.Id)
Dim maxId As Integer = ids.Max + 1
Dim newUser As Demo.User.Model.User = New Demo.User.Model.User With {
.Id = maxId, _
.Mail = name & "@abc.com", _
.Name = name _
}
users(maxId) = newUser
Return newUser
End Function
使用上面的 jQuery 代码,我没有收到错误或异常消息,甚至没有达到它的操作。但是,如果我从代码隐藏测试操作(我正在通过 Web 表单项目实现 Web Api),则会调用该操作。这是我从代码隐藏中测试的方式
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim client As New WebClient()
Dim data As New NameValueCollection()
data.Add("name", "Pedro")
Dim response As Byte() = client.UploadValues("http://localhost/Demo/api/user", "POST", data)
lbl.Text = Encoding.ASCII.GetString(response)
End Sub
那么,我的问题是,为什么我的 js 代码无法访问 web Api 操作?
在你问之前,我使用$.stringify("="+data),,因为我用this code扩展了jQuery,我这样做是因为我需要支持旧版本的IE。
我也查了this question,没有成功
更新:我已经在 Chrome 上调试了该网站,并收到了 404 error。出于某种原因,数据对象是这样发送的http://localhost/Demo/[object%20Object]
【问题讨论】:
-
你有没有尝试做一个简单的不带参数的POST?
-
我做了,结果相同,没有警报,没有错误......什么都没有:(
-
Firebug或其他浏览器开发工具对请求/响应显示什么? -
您是否尝试将 [HttpPost] 属性添加到 PostUser 方法中?
-
@Dusan 我已经在 Chrome 上调试了该网站,我得到了一个
404 error。出于某种原因,数据对象的发送方式如下http://localhost/Demo/[object%20Object]
标签: jquery asp.net vb.net asp.net-web-api