When receiving an object from a client on a Http API endpoint - and that object comes in as a C# object (FromBody
) - is there any way to detect if the client has added a property that is not part of the expected object?
Say for instance we were to receive an object of a class that was defined as:
public class SomeData
{
public int id { get; set; }
public string name { get; set; }
}
and the data that was sent from a client is
{
"id": 56,
"name": "JimBob",
"Something": "Some other piece of data not expected"
}
Is there any way to get told by the .NET data binders that we received an invalid property?
In terms of "being notified" of unexpected properties, there is no built-in way. Also, you can't simply tell model binder to "add any extra properties to a model". However, you can implement a middleware to intercept the received body data and alter it however you want. With such middleware, you can theoretically achieve what you want.
Here is what I did in a project. It involved taking data from body and parsing it into a meaningful model.
And register the middleware like this. You can put it just before routing middleware:
And here is how you would use the custom request data in your controller actions:
In theory, you can parse body into your expected model (which contain all expected properties), and add a
Dictionary<string, string>
property and add any extra/unexpected properties into it as a key-value pair. ThekeyValuePairs
variable in middleware will contain everything in the request body. What the middleware does is inject an object intoHttpContext.Items
, which you can access within the same request scope in preceding handlers, similar to passing aViewData
orTempData
to views.All that being said, you should keep security in mind. Accepting any extra properties seems like a risky approach. Having a predefined list of all expected properties would be an infinitely healthier approach.