我正在开发一个 ASP.NET Web API,其中一个方法将以下模型作为输入参数
public InputModel
{
int Id {get; set;}
bool? IsTrue {get; set;}
}
它适用于 true 和 false 值。我试图检查它对非 bool 值的行为。所以我提供了输入并得到了一些结果
isTrue = 0 -> model set to false
isTrue = 1 -> model set to true
isTrue = 2 -> model set to true
isTrue = -1 -> model set to true
这是我没想到的。该模型对所有非零整数都设置为真
我如何配置模型绑定(bind)器以仅在 bool 输入上设置值而不是整数输入(可能会给出一些验证错误)?
最佳答案
可以如下定义属性的set方法:
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;
}
}
}
}
关于c# - 防止整数值在 ASP.NET Web API 模型绑定(bind)中设置 bool 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49798050/