When a web api expects an int value, if the client sends null or empty string in JSON, it is automatically converted to 0. How can I prevent this? Is there such a configuration? I want it to throw an error since it is not what it expects.
3 Answers
You can annotate your DTO / property with the JsonPropery attribute and mark it as required:
public class MyDto
{
[JsonProperty(Required = Required.Always)]
public int RequiredProperty { get;set; }
}
With this attribute, JsonConvert.DeserializeObject() will throw an exception if no value for the property is specified in the JSON string.
See here for an example: https://dotnetfiddle.net/TstCau
2 Comments
'RequiredProperty' : ''. If I understand correctly, that's what you want. (see dotnetfiddle.net/Fhy5Bf)You can allow null inside an integer by declaring it as "int?"
After this you can just check if the variable is equal to null and give an error message.
2 Comments
This solution is also rather a hack and should not be used on a regular basis. But here we go.
I had a problem - I wanted to accept enums on my API as strings, but wanted to have them in my code as enums, not strings.
I just put an extra property (may put some data attribute there, like [NotMapped]) and overrode getters and setters like the following
/// <summary>
/// Required. A type of the metric for which data is requested.
/// </summary>
public Metrics MetricType { get; set; }
[Required]
/// <summary>
/// Alias for MetricType.
/// </summary>
public string Type
{
get
{
return MetricType.ToString();
}
set
{
try
{
MetricType = value.ToEnum<Metrics>();
}
catch (System.Exception)
{
throw new ArgumentException("Invalid Type parameter.");
}
}
}
I think you may override conversion logic like that. Check your string for null or empty and assign proper value to your int.