'Convert int values (1,0) to boolean using FromQueryAttribute
I have this API method:
[HttpGet("foo")]
public IActionResult Foo([FromQuery] bool parameter)
{
// ...
}
And I know I can call my method like this and it will work:
.../foo?parameter=true
But I also want to support numeric values 0 and 1 and call my method like this:
.../foo?parameter=1
But when I try, I get this exception inside System.Private.CoreLib
System.FormatException: 'String '1' was not recognized as a valid Boolean.'
Is this even possible?
Solution 1:[1]
Because the default ModelBinder didn't support 1 to bool, we can try to create our own binding logic by implementing IModelBinder interface.
public class BoolModelBinder : IModelBinder {
public Task BindModelAsync(ModelBindingContext bindingContext) {
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).FirstValue;
if (int.TryParse(value, out var intValue)) {
bindingContext.Result = ModelBindingResult.Success(intValue == 1);
} else if (bool.TryParse(value, out var boolValue)) {
bindingContext.Result = ModelBindingResult.Success(boolValue);
} else if (string.IsNullOrWhiteSpace(value)) {
bindingContext.Result = ModelBindingResult.Success(false);
}
return Task.CompletedTask;
}
}
then we can use ModelBinderAttribute to assign our BoolModelBinder type as this binder.
[HttpGet("foo")]
public IActionResult Foo([ModelBinder(typeof(BoolModelBinder))] bool parameter)
{
// ...
}
Solution 2:[2]
the easiest way is to change an input parameter type to string
[HttpGet("foo")]
public IActionResult Foo([FromQuery] string parameter)
{
if( parameter=="true" || parameter=="1") ....
else if( parameter=="false" || parameter=="0") ....
else ....
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | D-Shih |
| Solution 2 | Serge |
