Asp.net Core模型绑定程序接受布尔类型的随机整数 [英] Asp.net Core model binder accepts random integer for boolean types

查看:113
本文介绍了Asp.net Core模型绑定程序接受布尔类型的随机整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于模型具有布尔属性:

Given the model has a boolean property:

public class Person
{
    public string Name { get; set; }
    public bool IsMale { get; set; }
}

尝试发布以下有效负载时:

When trying to POST the following payload:

{
    "name": "Bob",
    "isMale": 12345 // any random integer
}

一个简单的动作:

[HttpPost]
public IActionResult Post([FromBody] Person person)
{
    if (ModelState.IsValid)
        return Ok();
    return BadRequest(ModelState);
}

person.IsMale属性获取true的值.

如果通过isMale: "foobar",我将收到无效的类型错误

If passing isMale: "foobar" i get an invalid type error

如果通过isMale: "0",我将收到无效的类型错误

If passing isMale: "0" i get an invalid type error

如果通过isMale: "1",我将收到无效的类型错误

If passing isMale: "1" i get an invalid type error

如果通过isMale: "True",我会得到true

如果通过isMale: "False",我会得到false

如果通过isMale: 0,我会得到false

如果通过isMale: 1,我会得到true

如果传递isMale: 34(随机整数),我得到true

If passing isMale: 34 (a random int) i get true

为什么认为随机整数默认为true,以及如何更改该行为以抱怨传入的类型不合适(用int代替bool)?

Why it considers that a random integer defaults to true and how to change that behaviour to complain that the type passed in is inappropriate (int instead of bool)?

推荐答案

也许这不是一个完美的解决方案,但是一旦您将JSON作为请求正文发送,这种解决方法便会满足您的需求:

Maybe it is not a perfect solution, but once you send JSON as a request body, such workaround should fit your needs:

public class Person
  {
    public string Name { get; set; }

    [JsonProperty("isMale")]
    public string IsMaleString { private get; set; }

    [JsonIgnore]
    public bool IsMale
    {
      get
      {
        return bool.TryParse(IsMaleString, out bool value)
          ? value
          : IsMaleString == "1";
      }
    }
  }

对于'true'和'1'的变化,它将返回'true',否则将为'false'

In case of variations of 'true' and '1' it'll return 'true', otherwise it'll be 'false'

这篇关于Asp.net Core模型绑定程序接受布尔类型的随机整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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