Currently I'm passing Rest Request with JSON string as filter to Web API as follows,
http://localhost:13825/api/values/get?filter={"Name":"abcdef","Address":"Something"}
I have a class like follows,
Public class Customer
{
public string Name{get;set;}
public string Address{get;set;}
}
When I use the following code to parse JSON string to a class object it works fine,
public string Get(Customer filter)
{
}
The problem is, When I pass filter like follows,
filter={"Name":"abcdef","Adess":"Something"}
my code assigns null value to Address property of Customer class but i wanted to throw an error when a property from JSON string is not found in any of the class property.
We can use MissingMemberHandling.Error but it will throw error when additional properties with all the properties what we defined in class . Here the problem case is different , I wont pass Address and Name properties every time. I may or may not pass both.
So I cant give required property.
I need to throw an error when unknown property is found in input JSON string.
You can set JsonSerializerSettings.MissingMemberHandling
to MissingMemberHandling.Error
.
Gets or sets how missing members (e.g. JSON contains a property that isn't a member on the object) are handled during deserialization.
If you want to do this globally, for all controllers, simply add this to global.asax
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.MissingMemberHandling = MissingMemberHandling.Error;
If you want to do this for a specific action/controller, then you have to implement IControllerConfiguration
:
public class RejectUnrecognizedPropertiesAttribute : Attribute, IControllerConfiguration
{
public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)
{
controllerSettings.Formatters.Remove(controllerSettings.Formatters.JsonFormatter);
var formatter = new JsonMediaTypeFormatter
{
SerializerSettings =
{
MissingMemberHandling = MissingMemberHandling.Error
}
};
controllerSettings.Formatters.Add(formatter);
}
}
And simply apply the [RejectUnrecognizedProperties]
attribute to your action/controller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With