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?
CodePudding user response:
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 ....
}
CodePudding user response:
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)
{
// ...
}