AJAX将多个参数传递给WebApi

Moh*_* JK 5 asp.net jquery asp.net-web-api

AJAX请求:

$.ajax({
            url: url,
            dataType: 'json',
            type: 'Post',
            data: {token:"4", feed:{"id":0,"message":"Hello World","userId":4} }
        });
Run Code Online (Sandbox Code Playgroud)

服务器端Web API:

 [HttpPost]
 public HttpResponseMessage Post(string token, Feed feed)
 {
    /* Some code */

    return new HttpResponseMessage(HttpStatusCode.Created);
 }
Run Code Online (Sandbox Code Playgroud)

错误代码404:{"message":"找不到与请求URI匹配的HTTP资源'localhost:8080/api/feed'.","messageDetail":"在控制器'Feed'上找不到与之匹配的操作请求."}

为什么我收到此错误以及为什么我无法将多个参数POST到我的API?

Dar*_*rov 12

首先编写视图模型:

public class MyViewModel
{
    public string Token { get; set; }
    public Feed Feed { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

您的控制器操作将作为参数:

[HttpPost]
public HttpResponseMessage Post(MyViewModel model)
{
    /* Some code */

    return new HttpResponseMessage(HttpStatusCode.Created);
}
Run Code Online (Sandbox Code Playgroud)

最后调整你的jQuery调用将其作为JSON发送:

$.ajax({
    url: url,
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({
        token: '4',
        feed: {
            id: 0,
            message: 'Hello World',
            userId: 4
        } 
    })
});
Run Code Online (Sandbox Code Playgroud)

AJAX调用需要注意的重要事项:

  • 将请求设置contentTypeapplication/json
  • 将数据包装在JSON.stringify函数中以有效地将javascript对象转换为JSON字符串
  • 删除了无用的dataType: 'json'参数.jQuery将自动使用Content-Type服务器发送的响应头来推断如何解析传递给success回调的结果.


chr*_*dev 1

您可以发布您的Feed课程吗,只是为了确保属性匹配。

var data = {
     token: "4",
     feed: {Id:0,Message:"Hello World",UserId:4}
}

$.ajax({
            url: "/api/Feed/",
            dataType: 'json',
            type: 'Post',
            data: JSON.stringify(data)
        });
Run Code Online (Sandbox Code Playgroud)