19

I get error when passing the parameters,

"Can't 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) {

    },
})
3
  • Possible duplicate of WebAPI Multiple Put/Post parameters Commented Jun 16, 2017 at 22:59
  • Dear Paul. I just checked the mention question this is not duplicate because that question is different than my current question. Thank you Commented Jun 16, 2017 at 23:26
  • Are you using Web API 1 or 2? Commented Jun 16, 2017 at 23:53

1 Answer 1

42
+50

Reference: 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.

emphasis mine

That being said. You need 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 action to expect that model in the body

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

making sure to send the payload properly

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) {

    },
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.