避免将任何数字绑定到bool属性 [英] Avoid bind any number to bool property

查看:74
本文介绍了避免将任何数字绑定到bool属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有带模型的简单ASP.NET Core WebApi

I have simple ASP.NET Core WebApi with model

public class Model
{
    public bool? Value {get; set;}
}

和端点

[HttpPost]
public async Task<IActionResult> Create([FromBody] Model model)

当我用body发出POST请求

When I make a POST request with body

{
   "Value" : 7676
}

{
   "Value" : 2955454545645645645645645645654534534540    
}

然后 model.Value == true

如何避免这种情况?在这种情况下,我需要一些错误,因为 7676 不是布尔值.

How to avoid this? I need some error in this case, because 7676 is not the Boolean value.

我发现了这个问题,但是解决方案不适合我,因为我在不同的项目中有很多模型(因此,很难将JsonConverter属性(从答案到所有属性)添加进来

I found this question and this, but solution is not fit for me, because I have a many models in different projects (so, it will hard to add JsonConverter attribute, from answer, to all properties)

此外,我正在寻找描述此行为的所有文档.

Also, I'm looking for any docs that describes this behavior.

推荐答案

您可以通过创建自定义JsonConverter来实现.可以在此处

You can achieve it by creating a custom JsonConverter. The documenation for the same can be found here

此行为的原因与JSON.NET或 System.Text.JSON 反序列化类型的方式有关.由于123可以转换为 boolean true,因此反序列化成功.它会根据整数值认为是true还是false,直到您按如下所示显式定义一个JsonConverter来检查所读取的令牌是否为布尔值为止.

The reason for this behavior has got to do with the way JSON.NET or System.Text.JSON deserializes types. Since 123 can be converted to boolean true, deserialization is successful. It considers it to be true or false depending upon the integer value until you explicitly define a JsonConverter as below that checks the token being read is actually boolean.

如果您不使用Newtonsoft.您可以使用 System.Text.Json .您可以按照此页面进行

,然后将您的模型装饰为:

and then decorate your model as:

public class Model
{
    [JsonConverter(typeof(OnlyBoolean))]
    public bool? Value {get; set;}
}

或在启动中全局注册

services.AddMvc().AddJsonOptions(options => { options.SerializerSettings.Converters.Add(new OnlyBoolean());});

这篇关于避免将任何数字绑定到bool属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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