通过AJAX将JSON数据发布到Web API

时间:2016-07-04 11:54:45

标签: jquery json ajax asp.net-mvc

我在尝试通过AJAX POST请求将JSON对象传递给Web API时遇到了麻烦。 这是我的AJAX POST请求

<li><a href="#register">Register</a></li>

$('#usrRegister').click(function () {
                var uname = $('#usrName').val();
                var uloginname = $('#usrLoginName').val();
                var uemail = $('#usrEmail').val();
                var upwd = $('#usrPwd').val();

                var registerObj = {
                    "name": uname,
                    "username": uloginname,
                    "email": uemail,
                    "password": upwd

                };
                console.log("registerObj :", registerObj);

                $.ajax({                    
                    url: "http://localhost:54118/api/UserApi",
                    type: "POST",
                    //contentType: "application/x-www-form-urlencoded",
                    data: JSON.stringify(registerObj),
                    contentType: "application/json",
                    success: function (data) {
                        alert("Successfully Registered..");
                    },
                    error: function (xhRequest, ErrorText, thrownError) {
                        alert("Failed to process correctly, please try again");
                    }
                });
            });

API:

[HttpPost]
public void Post(tblUser userdata)
{
    obj.tblUsers.Add(userdata);
    try
    {
    obj.SaveChanges();
    }
    catch (System.Data.Entity.Validation.DbEntityValidationException ex)
    {
    foreach (var e in ex.EntityValidationErrors)
    {
        //check the ErrorMessage property
    }
    }
}

当我点击注册时,它在控制台anonymous function处显示$.ajax({,而API未调用。但是当我用application/x-www-form-urlencoded而不是application/json替换contentType时,API正在调用,但将所有字段显示为null。当我在REST客户端中调用相同的API时,它工作正常。帮助我解决导致问题的原因。

2 个答案:

答案 0 :(得分:2)

感谢您的回复。它正在使用此代码。我添加了 xhrFields: 'withCredentials:true'contentType: 'application/x-www-form-urlencoded'

         $.ajax({                    
                    url: "http://localhost:54118/api/UserApi",
                    xhrFields: 'withCredentials:true',
                    type: "POST",
                    data: {
                                "name": uname,
                                "username": uloginname,
                                "email": uemail,
                                "password": upwd
                            },
                    contentType: 'application/x-www-form-urlencoded',
                    success: function (data) {
                        alert("Successfully Registered..");
                    },
                    error: function (xhRequest, ErrorText, thrownError) {
                        alert("Failed to process correctly, please try again");
                    }
                });

答案 1 :(得分:2)

尝试在参数中添加[FromBody]前缀。

像这样: public void Post([FromBody] tblUser userdata)

然后,您应该可以再次使用application/json