阻止整数值在ASP.NET Web API模型绑定中设置布尔参数? [英] Prevent integer values to set boolean parameter in ASP.NET Web API model binding?

查看:36
本文介绍了阻止整数值在ASP.NET Web API模型绑定中设置布尔参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发ASP.NET Web API,其中一种方法将以下模型作为输入参数

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;}
}

它使用true和false值.我尝试检查非布尔值的行为.所以我提供了输入并得到了一些结果

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->模型设置为false
isTrue = 1->模型设置为true
isTrue = 2->模型设置为true
isTrue = -1->模型设置为true

isTrue = 0 -> model set to false
isTrue = 1 -> model set to true
isTrue = 2 -> model set to true
isTrue = -1 -> model set to true

这是我没想到的.所有非零整数的模型均设置为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)?

推荐答案

您可以如下定义属性的set方法:

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;
            }
        }
    }
}

这篇关于阻止整数值在ASP.NET Web API模型绑定中设置布尔参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆