Reputation: 5369
I seem to have run into an interesting problem with Web API - using this controller action, with a breakpoint on the opening brace to inspect thing
:
[HttpPut]
public void Test([FromBody]object thing)
{
}
If I submit the following request (as CURL), I get the expected value which is a JObject containing the data from the body:
curl -X PUT -H "Content-Type: application/json" -d '{
"Name": "Joe",
"Key": { "Key": "Value" }
}' "http://localhost/api/TestController/Test"
That is, an anonymous object where Name
is Joe and Key
is another object containing Key = Value
.
However, if I change this ever-so-slightly to instead submit an array of Keys
, I get null
. No error, just null
.
curl -X PUT -H "Content-Type: application/json" -d '{
"Name": "Joe",
"Keys": [{ "Key": "Value" }]
}' "http://localhost/api/TestController/Test"
Why is this happening? The HTTP verb doesn't seem to matter (I've tried POST and PUT), and using dynamic
instead of object
is the same thing.
Upvotes: 1
Views: 9359
Reputation: 85
i think it all depends on how you wish to work with it, if you want to get a strongly typed model you can always create one like user3658685 said.
another thing you can do is bind the data to JObject and then serialize using Newton-soft Serializer:
public void Post([FromBody] JObject value)
{
//instead of object you can use any type you wish to cast
object obj = value.ToObject<object>();
}
Upvotes: 1
Reputation: 1
WebApi uses model mapping class to try to map json object with the argument og your WebApi method. You can resolve this by creating a class with all attributes matching your json object.
public class Contract {
public string Name { get; set; }
public dynamic[] Keys { get; set; }
}
And changing the signature of your WebApi method with
public void Post([FromBody] Contract value)
{
}
Upvotes: 0
Reputation: 5369
Turns out I had the global JSON setting for MaxDepth
set to 2
elsewhere in my code, which was running before the controller action. Why this returns null
and not an empty object is still beyond me, but changing this to 3
corrects the issue and functions as expected.
Sorry for the confusion everyone, thanks for the answers!
Upvotes: 1