Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you post an anonymous object as json to a webapi method and it match the properties of the json object to the parameters of the webapi call?

Can I have a webapi method

[Route("someroute")]
public void SomeMethod(string variable1, int variable2, Guid variable3)
{
     //... Code here
}

simple json

var jsonvariable = new {
    variable1:"somestring",
    variable2:3,
    variable3: {9E57402D-8EF8-45DE-B981-B8EC201D3D8E}
}

Then make the post

HttpClient client = new HttpClient { BaseAddress = new Uri(ConfigurationManager.AppSettings["SomeURL"]) };
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.PostAsJsonAsync("someroute", jsonvariable ).Result

Coming from javascript I can do something like this and it resolves the individual properties but I can't seem to do it with a C# call

var postData = {
     appUniqueId: appUniqueId
};

$http
   .post('someurl', postData)
   .success(function(response) {
      defer.resolve(response.data);
   });

webapi method
SomeWebMethod(Guid appUniqueId) <-- same name as in postdata
like image 600
DRobertE Avatar asked Jun 13 '14 20:06

DRobertE


1 Answers

You can't quite go about it like you are doing there.

As mentioned in the comments and in this article, you may only use one FromBody parameter for your method. Thus, one or none of those parameters are going to be bound from your JSON body. If any of them, it may be the guid that it tries to bind simply because of the web api parameter binding rules involved.

How do you get around this? Make a class that is how your data is described.

public class SomeBodyParameters
{
     public string variable1 { get; set; } 
     public int variable2 { get; set; } 
     public Guid variable3 { get; set; } 
} 

Then your api method would look like this:

[Route("someroute")]
public void SomeMethod([FromBody]SomeBodyParameters parameters)
{
     //... Code here
}

The stipulation is that it won't automagically bind based on type, but rather the name that you set in your example anonymous type. variable1, variable2, and variable3 must have their names match in both spots.

When you think about it, that anonymous type that looks like JSON really is passing in a sort of object, so really that's what you should be accepting back anyway.

Food for thought: How would you be able to differentiate between a simple "string" and an object that has a singular string like var jsonvariable = new { variable1:"somestring"};? You basically couldn't and the two probably shouldn't be equivilant.

like image 176
Zachary Dow Avatar answered Sep 30 '22 07:09

Zachary Dow