web api post 方法可以包含多个参数吗?
Can a web api post method contains more than one parameter?
我在网络的控制器中有这个方法api
public class UserController : ApiController
{
[HttpPost]
public HttpResponseMessage Login(string name, string password){
//dothings
}
}
但是如果我尝试 ajax 请求:
$.ajax({
type: "POST",
url: "http://localhost:19860/Api/User/Login",
data: { name: "name", password: "12345" },
success: succ,
error: err
});
它给我错误:
消息:"No HTTP resource was found that matches the request URI 'http://localhost:19860/Api/User/Login'."
消息详细信息:"No action was found on the controller 'User' that matches the request."
但是,如果我删除参数,它会起作用!
public class UserController : ApiController
{
[HttpPost]
public HttpResponseMessage Login(){
string name= HttpContext.Current.Request.Params["name"];
string password= HttpContext.Current.Request.Params["password"];
// name and password have the value that i passed in the ajax call!!
}
}
为什么会这样?
由于与这个问题无关的原因,我无法更改网络api,所以我必须维护:
public HttpResponseMessage Login(string name, string password)
格式。
我可以保持这种格式并能够进行 ajax 调用吗?
您不能 post Web-API 方法的多个参数,如 this blog post
中所述
除此之外别无选择,如下所示。
1。尝试在 queryString 上传递它。
更改您的 ajax 函数调用,如下所示。
$.ajax({
type: "POST",
url: "http://localhost:19860/Api/User/Login?name=name&pass=pass",
data: { name: "name", password: "12345" },
success: succ,
error: err
});
你将得到 name = name 和 password = pass 在你的 api 控制器中。
2。按照 this blog post.
中的实施创建您自己的活页夹
3。将所有 Web-API 方法参数包装在一个对象或类型中(推荐)。
从上面你可以使用你在问题中提到的第一种和第二种方法你不能改变你的api方法签名。
我在网络的控制器中有这个方法api
public class UserController : ApiController
{
[HttpPost]
public HttpResponseMessage Login(string name, string password){
//dothings
}
}
但是如果我尝试 ajax 请求:
$.ajax({
type: "POST",
url: "http://localhost:19860/Api/User/Login",
data: { name: "name", password: "12345" },
success: succ,
error: err
});
它给我错误:
消息:"No HTTP resource was found that matches the request URI 'http://localhost:19860/Api/User/Login'." 消息详细信息:"No action was found on the controller 'User' that matches the request."
但是,如果我删除参数,它会起作用!
public class UserController : ApiController
{
[HttpPost]
public HttpResponseMessage Login(){
string name= HttpContext.Current.Request.Params["name"];
string password= HttpContext.Current.Request.Params["password"];
// name and password have the value that i passed in the ajax call!!
}
}
为什么会这样?
由于与这个问题无关的原因,我无法更改网络api,所以我必须维护:
public HttpResponseMessage Login(string name, string password)
格式。
我可以保持这种格式并能够进行 ajax 调用吗?
您不能 post Web-API 方法的多个参数,如 this blog post
中所述除此之外别无选择,如下所示。
1。尝试在 queryString 上传递它。
更改您的 ajax 函数调用,如下所示。
$.ajax({
type: "POST",
url: "http://localhost:19860/Api/User/Login?name=name&pass=pass",
data: { name: "name", password: "12345" },
success: succ,
error: err
});
你将得到 name = name 和 password = pass 在你的 api 控制器中。
2。按照 this blog post.
中的实施创建您自己的活页夹3。将所有 Web-API 方法参数包装在一个对象或类型中(推荐)。
从上面你可以使用你在问题中提到的第一种和第二种方法你不能改变你的api方法签名。