Reputation: 564
I'm looking for a way to detect extra attributes delivered on a WebAPI post payload that do not match the POCO I expect. For example, here's an input object:
public class Input
{
public string Name { get; set; }
}
And a controller method:
public void Post([FromBody]Input value)
If a client sends the following post payload:
{
"Name" : "Foo",
"Description" : "Bar"
}
This will trigger the Post method on my controller and Name will be populated. I'd like to be aware that Description was sent but ignored, so I can either log that event server side or inform the client through a response header that they're sending extra data.
Upvotes: 2
Views: 200
Reputation: 4250
I think this is possible but you'd have to go without Model Binding and use reflection if you want a general solution:
Class:
public class Input
{
public string Name { get; set; }
}
Payload:
{
"Name" : "Foo",
"Description" : "Bar"
}
Controller Method:
public async void Post()
{
//Read the content to a string
var content = await Request.Content.ReadAsStringAsync();
//Get the Input object you wanted
var input = JsonConvert.DeserializeObject<Input>(content);
//Get a Dictionary containing all the content sent
var allContent = JsonConvert.DeserializeObject<Dictionary<string, object>>(content);
//Get the property names of the wanted object
var props = input.GetType().GetProperties().Select(a => a.Name);
//See which properties are extra
var extraContent = allContent.Keys.Except(props);
}
For the above example extraContent would be a list containing "Description". If you want the value just use the dictionary object.
Upvotes: 2