c# - 防止整数值在 ASP.NET Web API 模型绑定(bind)中设置 bool 参数?

标签 c# asp.net asp.net-web-api

我正在开发一个 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/

相关文章:

c# - 使用MVVM从页面的OnNavigate调用Viewmodel中存在的方法

c# - 如何将文件下载到远程机器,就像我在自己的机器上一样或类似?

c# - 如何暂停控件及其子项的绘制?

c# - .aspx 代码错误 "Element ' xxxx' 不受支持。”

asp.net - VS 2010 中缺少 App_Code 文件夹

javascript - ASP.NET Resource resx String 工具提示显示帮助

.net - Microsoft.WindowsAzure.Messaging.NotificationHub 和 Microsoft.Azure.NotificationHubs.NotificationHubClient 之间有什么区别?

c# - WebAPI : custom parameter mapping

c# - C#混淆中字符串加密的安全性

c# - 如果我不打算将数据保存到 SQL 数据库中,我应该将它保存在哪里?