Reputation: 2719
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.
Upvotes: 4
Views: 13449
Reputation: 13488
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.
Upvotes: 5
Reputation: 7866
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"
}
Upvotes: 4
Reputation: 14669
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);
});
Upvotes: 1