2017-06-16 47 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 /後置參數]的