Prevent integer values to set boolean parameter in ASP.NET Web API model binding?

纵然是瞬间 提交于 2020-02-01 05:06:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!