如何使用 web-api 传递多个参数
How to pass multiple parameters using web-api
我想在 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"
});
}
// 登录控制器
[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;
}
[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"
});
}
除了@su8898 指出的 GET 与 POST 问题之外,您已经在 details
中构建了一个字符串,然后尝试 stringify
它。您应该像这样将详细信息定义为对象文字:
var details = {
'email': email,
'pass': password
};
这将为您提供 stringify
的实际对象。
我想在 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"
});
}
// 登录控制器
[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;
}
[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"
});
}
除了@su8898 指出的 GET 与 POST 问题之外,您已经在 details
中构建了一个字符串,然后尝试 stringify
它。您应该像这样将详细信息定义为对象文字:
var details = {
'email': email,
'pass': password
};
这将为您提供 stringify
的实际对象。