I have a dynamic object (it's actually json) that I pass into my MVC WebApi controller.
The json object contains multiple lists within an anonymous object that are submitted to the controller from another application via client.PostAsJsonAsync("myapiurl", objectGraph)
.
What I need to do to validate the object on the MVC side, is to get the count of objects in each list. I can access the lists dynamically via mydynamicobject.mylist
and individual items via mydynamicobject.mylist[index]
but I can't seem to be able to get a count of mydynamicobject.mylist
.
What I've tried so far:
- LINQ extension methods - doesn't work on dynamic
Enumerable.Count(mydynamicobject.mylist)
- can't infer type
Any other ideas? The count is actually correctly available in the dynamic object's base
but obviously not accessible as a property. Help!
This works now:
// This is a MVC/WebApi method
public dynamic Post(dynamic mydynamicobject)
if (((ICollection)mydynamicobject.mylist).Count == 0)
{
// do something
}
The code that sends the dynamic object (different app):
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add
(new MediaTypeWithQualityHeaderValue("application/json"));
var objectGraph = new { mylist = new { Id = 1 }, mylist2 = new { Name = "ABC" } };
var r = client.PostAsJsonAsync("api/mycontroller", objectGraph).Result;