ajax 调用 web-api 对 GET 有效但对 POST 无效

ajax call to web-api worked for GET but not working for POST

我的javascript函数:

function CheckLogin() {
        var user = { "UserName": $('#UN').val(), "Password": $('#P').val() };
       $.ajax({

            url: 'http://localhost/MvcRazorClient/api/HomeApi/SignIn',
            type: 'POST',
            data: user,
            async: false,
            contentType:'application/json',
            dataType: 'json',
            success: function (data) {
                if (data == true)
                {

                    alert('true');

                }
                else{
                    alert('false');
                }


                    },
                    error: function () {
                        alert('error');

                    }
                });
            }

我的网络-api方法:

[HttpPost]
public bool SignIn(string UserName, string Password)
{
return true;
}

当我使用 GET 请求时,我能够传递数据,即用户到网络-api,但当使用 POST 时,我无法传递。 请帮忙

创建一个 C# 对象,如:

public class User
{
  public string UserName {get;set;}
  public string Password {get;set;}
}

然后更新您的控制器以接收用户而不是两个字符串,例如

[HttpPost] 
public bool SignIn(User user) 
{ 
  return true; 
}

您可能还需要更新 javascript 对象,因为 ajax 调用告诉服务器需要一个 json 对象,您可能需要在用户对象创建行中

var user = { "userName": $('#UN').val(), "password": $('#P').val() };
function CheckLogin() {
        var user = { "UserName": $('#UN').val(), "Password": $('#P').val() };
        user = JSON.stringify(user);//changes made here
       $.ajax({

            url: 'http://localhost/MvcRazorClient/api/HomeApi/SignIn',
            type: 'POST',
            data: user,
            async: false,
            contentType:'application/json',
            dataType: 'json',
            success: function (data) {
                if (data == true)
                {

                    alert('true');

                }
                else{
                    alert('false');
                }


                    },
                    error: function () {
                        alert('error');

                    }
                });
            }

我的网络-api方法:

[HttpPost]
public bool SignIn(HttpRequestMessage req)//changes made here
{
var data = req.Content.ReadAsStringAsync().Result;// to extract data
      JObject o = JObject.Parse(data);
return true;
}