2017-06-16 46 views
5

传递参数,当我得到的错误,MVC的Web API,错误:无法绑定多个参数

"Can't bind multiple parameters"

这里是我的代码

[HttpPost] 
public IHttpActionResult GenerateToken([FromBody]string userName, [FromBody]string password) 
{ 
    //... 
} 

阿贾克斯:

$.ajax({ 
    cache: false, 
    url: 'http://localhost:14980/api/token/GenerateToken', 
    type: 'POST', 
    contentType: "application/json; charset=utf-8", 
    data: { userName: "userName",password:"password" }, 

    success: function (response) { 
    }, 

    error: function (jqXhr, textStatus, errorThrown) { 

     console.log(jqXhr.responseText); 
     alert(textStatus + ": " + errorThrown + ": " + jqXhr.responseText + " " + jqXhr.status); 
    }, 
    complete: function (jqXhr) { 

    }, 
}) 
+0

可能的复制( https://stackoverflow.com/questions/14407458/webapi-multiple-put-post-parameters) –

+0

亲爱的保罗。 我刚刚检查提到的问题,这不是重复的,因为这个问题是不同于我目前的问题。谢谢 – Tom

+0

您使用的是Web API 1还是2? –

回答

11

参考:Parameter Binding in ASP.NET Web API - Using [FromBody]

At most one parameter is allowed to read from the message body. So this will not work:

// Caution: Will not work!  
public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... } 

The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once.

重点煤矿

话虽这么说。您需要创建一个模型来存储预期的聚合数据。

public class AuthModel { 
    public string userName { get; set; } 
    public string password { get; set; } 
} 

,然后更新行动,以期望模型体内

[HttpPost] 
public IHttpActionResult GenerateToken([FromBody] AuthModel model) { 
    string userName = model.userName; 
    string password = model.password; 
    //... 
} 

确保发送有效载荷正常

var model = { userName: "userName", password: "password" }; 
$.ajax({ 
    cache: false, 
    url: 'http://localhost:14980/api/token/GenerateToken', 
    type: 'POST', 
    contentType: "application/json; charset=utf-8", 
    data: JSON.stringify(model), 
    success: function (response) { 
    }, 

    error: function (jqXhr, textStatus, errorThrown) { 

     console.log(jqXhr.responseText); 
     alert(textStatus + ": " + errorThrown + ": " + jqXhr.responseText + " " + jqXhr.status); 
    }, 
    complete: function (jqXhr) { 

    }, 
}) 
[的WebAPI多PUT /后置参数]的