我想在web-api中使用json传递两个参数,但每次尝试都会得到null,我错过了什么?是否有更好的方法来传递多个参数?
// HTML
var uri = "api/Login";
//点击按钮后,此功能触发
function checkUser() {
var email = "ttt@ggg.com";
var password = "itsme";
var details = "{ email:'"+ email+"', pass:'"+ password+"'}";
$.ajax({
type: "Get",
data: JSON.stringify(details),
url: uri,
contentType: "application/json"
});
}
// LoginController
[HttpGet]
public HttpResponseMessage Get([FromBody]string data)
{
HttpResponseMessage msg = null;
//the code run this function, but the 'data' is null
string userinfo = data;
return msg;
}
答案 0 :(得分:1)
除了@ su8898注意到的GET与POST问题之外,您已经在details
中构建了一个字符串,然后尝试stringify
它。您应该将详细信息定义为对象文字,如下所示:
var details = {
'email': email,
'pass': password
};
这将为您提供stringify
的实际对象。
答案 1 :(得分:0)
[FromBody]
属性不适用于GET
个请求,因为GET
请求中没有正文。
您必须将值作为参数传递或将方法更改为[HttpPost]
。我建议您将方法更改为[HttpPost]
,并将ajax
请求方法更改为POST
。
[HttpPost]
public HttpResponseMessage Get([FromBody]string data)
{
HttpResponseMessage msg = null;
//the code run this function, but the 'data' is null
string userinfo = data;
return msg;
}
并在您的ajax
请求中
function checkUser() {
var email = "ttt@ggg.com";
var password = "itsme";
var details = "{ email:'"+ email+"', pass:'"+ password+"'}";
$.ajax({
type: "POST",
data: JSON.stringify(details),
url: uri,
contentType: "application/json"
});
}