ozgur ozgur - 1 year ago 149
ASP.NET (C#) Question

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

When I have this method in an MVC Controller

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download