When I have this method in an MVC Controller
[HttpPost]
public async Task<ActionResult> MyMethod(int param1, string param2)
{
   //....
}
I can send a Json object {param1:1, param2:"str"} it works just fine and parameters are resolved. However when I do this for a WebApi 2 it doesn't work. Because [FromBody] can only be used by 1 parameter according to following example on documentation.
At most one parameter is allowed to read from the message body
    // Caution: Will not work!    
    public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }
How can we obtain the same behavior of MVC controller from WebApi controller?
Edit: Creating corresponding classes and replacing parameters is not an option, because a messaging tool checks these methods for maintenance. Signatures should remain the same.
Try to compose one object from these values:
public class Foo
{
    public int id {get;set;}
    public int name {get;set;}
}
public HttpResponseMessage Post([FromBody] Foo foo) 
{
    //some stuff...
}
If signature should remain the same, you can try to specify params in url, like that: myurl?id=1&name=Tom still via POST verb.
You can try like this:
public HttpResponseMessage Post([FromBody]dynamic value)
{
    int id= value.id.ToString();
    string name = value.name.ToString();
}
And pass json like following
{
  "id":"1",
  "name":"abc"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With