问题
I am developing an ASP.NET Web API in which a method takes below model as an input parameter
public InputModel
{
int Id {get; set;}
bool? IsTrue {get; set;}
}
It works with true and false value. I tried to check how it behaves for non-boolean values. So I provided inputs and got some results
isTrue = 0 -> model set to false
isTrue = 1 -> model set to true
isTrue = 2 -> model set to true
isTrue = -1 -> model set to true
This is something that I didn't expect. The model is set to true for all non-zero integers
How can I configure the model binder to set values only on boolean inputs and not on integer inputs(maybe give some validation error)?
回答1:
You can define the set method of the property as follows:
public InputModel
{
int Id {get; set;}
private bool istrue;
bool? Istrue
{
get
{
return istrue;
}
set
{
if (value.GetType() == typeof(bool))
{
istrue = value;
}
else
{
istrue = false;
}
}
}
}
来源:https://stackoverflow.com/questions/49798050/prevent-integer-values-to-set-boolean-parameter-in-asp-net-web-api-model-binding