Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind Json parameters to Web Api parameters in ASP.NET?

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.

like image 679
ozgur Avatar asked Oct 28 '25 18:10

ozgur


2 Answers

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.

like image 153
Slava Utesinov Avatar answered Oct 30 '25 08:10

Slava Utesinov


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"
}
like image 38
Divyang Desai Avatar answered Oct 30 '25 10:10

Divyang Desai