Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw error when unknown property found in input API request?

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.

like image 409
Rocky Avatar asked Mar 15 '23 22:03

Rocky


1 Answers

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.

like image 164
dcastro Avatar answered Mar 19 '23 06:03

dcastro