Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebAPI Selfhost: Can't bind multiple parameters to the request's content

The below code are simplified to show the necessity. May I know what is wrong? I can't seems to retrieve two Parameters (A and B in this case) using the [FromBody] attribute.

The error message is "Can't bind multiple parameters ('A' and 'B') to the request's content"

It is perfectly fine if I have either A or B only.

Web API:

[Route("API/Test"), HttpPost]
public IHttpActionResult Test([FromBody] int A, [FromBody] int B)

Client:

HttpClient client = new HttpClient();
var content = new FormUrlEncodedContent(
    new Dictionary<string, string> {
        { "A", "123" },
        { "B", "456" }
    });
client.PostAsync("http://localhost/API/Test", content).Result;
like image 584
s k Avatar asked Aug 02 '16 08:08

s k


2 Answers

Web Api doesn't support multiple [FromBody] params I think. But you can use Api model, to passing more parameters to your api action.:

public class YourApiModel
{
    public int A{ get; set; }

    public int B { get; set; }

    //...other properties    
}

After that, you can simply use this in your API controller Test:

    // POST: api/test
    public IHttpActionResult Post([FromBody] YourApiModel model)
    {
        //do something
    }

Hope it help.

like image 188
Petr Tomášek Avatar answered Nov 14 '22 22:11

Petr Tomášek


Try the Web API code:

[DataContract]
public class Model
{
    [DataMember]
    public int A { get; set; }

    [DataMember]
    public int B { get; set; }
}

[Route("API/Test"), HttpPost]
public IHttpActionResult Test([FromUri] Model model)
like image 35
Fan TianYi Avatar answered Nov 14 '22 23:11

Fan TianYi