I have the following structure:
public class SampleEntity{
public string Name { get; set; }
public OtherEntity Relation { get; set; }
}
public class OtherEntity {
public string Name { get; set; }
}
When i make a call to update an object in my web.api with the following request body:
"{'Name':'Nome', 'Relation':''}"
The deserializer fills the object with null value, but i think the correct action is throw an exception like 'invalid value for field Relation' and i can return a status code 400.
I tried to make a custom converter to do this, but i'm not happy with the solution and i am quite concerned with the performance of this.
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.StartObject)
{
var @object = JObject.Load(reader);
var target = Activator.CreateInstance(objectType);
var objectProperties = target.GetType().GetProperties().Where(x => x.PropertyType.IsPrimitive == false && x.PropertyType != typeof(string));
foreach (var prop in objectProperties)
{
var value = @object[prop.Name];
if (value != null && value.ToString() == string.Empty)
throw new Exception();
}
serializer.Populate(@object.CreateReader(), target);
return target;
}
return reader.Value;
}
public OtherEntity Relation { get; set; }that it would be unexpected for Relation to be null. Why don't you just deserialize it, then check to see if it's null and thrown an exception if it is?