加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – AJAX将多个参数传递给WebApi

发布时间:2020-12-16 07:35:10 所属栏目:asp.Net 来源:网络整理
导读:AJAX请求: $.ajax({ url: url,dataType: 'json',type: 'Post',data: {token:"4",feed:{"id":0,"message":"Hello World","userId":4} } }); 服务器端Web API: [HttpPost] public HttpResponseMessage Post(string token,Feed feed) { /* Some code */ retur
AJAX请求:

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

服务器端Web API:

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

    return new HttpResponseMessage(HttpStatusCode.Created);
 }

Error Code 404: {“message”:”No HTTP resource was found that matches
the request URI ‘localhost:8080/api/feed’.”,”messageDetail”:”No action
was found on the controller ‘Feed’ that matches the request.”}

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

解决方法

首先编写视图模型:

public class MyViewModel
{
    public string Token { get; set; }
    public Feed Feed { get; set; }
}

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

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

    return new HttpResponseMessage(HttpStatusCode.Created);
}

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

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读