I have a simple Controller with a POST method.
My model has a property of type enum.
When I send valid values ,everything works as expected
{ "MyProperty": "Option2"}
or
{ "MyProperty": 2}
If I send an invalid string
{ "MyProperty": "Option15"}
it correctly gets the default value (Option1) but if I send an invalid int ,it keep the invalid value
{ "MyProperty": 15}
Can I avoid that and get the default value or throw an error?
Thanks
public class ValuesController : ApiController
{
[HttpPost]
public void Post(MyModel value) {}
}
public class MyModel
{
[JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
public MyEnum MyProperty { get; set; }
}
public enum MyEnum
{
Option1 = 0,
Option2,
Option3
}
Update
I know I can cast any int to an enum,that's not the problem.
@AakashM's suggestion solves half my problem,I didn't know about AllowIntegerValues
Now I correctly get an error when Posting an invalid int
{ "MyProperty": 15}
The only problematic case now is when I post a string which is a number (which is strange because when I send an invalid non numeric string it correctly fails)
{ "MyProperty": "15"}