2017-06-16 21 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

親愛なるPaul。 私は、この質問が私の現在の質問と異なるので、これは重複していないという言及の質問をチェックしました。ありがとうございます – 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/Postパラメータ]の
関連する問題