MVC Web API, Error: Unable to bind multiple parameters

I get an error while passing parameters,

"Unable to bind multiple parameters"

here is my code

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

Ajax:

 $.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) { }, }) 
+13
source share
1 answer

Link: Linking parameters in the ASP.NET web interface - using [FromBody]

No more than 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 can be stored in an unbuffered stream that can only be read once.

my accent

It is said. You need to create a model to store the expected aggregated data.

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

and then update the action to expect this model in the body

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

to send the payload correctly

 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) { }, }) 
+32
source

Source: https://habr.com/ru/post/1268924/


All Articles