问题
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
}
To a simple action:
[HttpPost]
public IActionResult Post([FromBody] Person person)
{
if (ModelState.IsValid)
return Ok();
return BadRequest(ModelState);
}
The person.IsMale property gets the value of true.
If passing isMale: "foobar" i get an invalid type error
If passing isMale: "0" i get an invalid type error
If passing isMale: "1" i get an invalid type error
If passing isMale: "True" i get true
If passing isMale: "False" i get false
If passing isMale: 0 i get false
If passing isMale: 1 i get true
If passing isMale: 34 (a random int) i get true
Question:
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)?
回答1:
Judging from your examples, any numeric value that is not 0 is interpreted as true which is not strange at all.
The quoted versions "0" and "1" are string types and cannot directly be parsed to bool.
See the documentation for bool.Parse(string).
回答2:
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";
}
}
}
In case of variations of 'true' and '1' it'll return 'true', otherwise it'll be 'false'
来源:https://stackoverflow.com/questions/56132879/asp-net-core-model-binder-accepts-random-integer-for-boolean-types