简体   繁体   中英

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.

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 have to pass multiple parameter please use class object :

public class PortalClass
{
    public ApplicationModel applicationModel { get; set; }
    public string user_id { get; set; }
    public string id { get; set; }
    public object pageCollection { get; set; }
}

public object GetApplication(PortalClass data)
{
    JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All, PreserveReferencesHandling = PreserveReferencesHandling.None };
    var myObject=JsonConvert.DeserializeObject<PageCollection>(data.pageCollection.ToString(), settings)
    return null;
}

Client Side:

var data = {
    user_id: userId,
    id: id
};

http.post(url, data).then(
   function (response) {

}, function (err) {
   callback.reject(err);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM