C# 自定义布尔参数绑定
我有一个WebApi方法,如下所示:C# 自定义布尔参数绑定,c#,model-binding,asp.net-web-api2,C#,Model Binding,Asp.net Web Api2,我有一个WebApi方法,如下所示: public string Get([FromUri] SampleInput input) { //do stuff with the input... return "ok"; } 输入定义如下: public class SampleInput { // ...other fields public bool IsAwesome { get; set; } } 实际上,它工作正常:如果我在查询字符串中传递&isAwe
public string Get([FromUri] SampleInput input)
{
//do stuff with the input...
return "ok";
}
输入定义如下:
public class SampleInput
{
// ...other fields
public bool IsAwesome { get; set; }
}
实际上,它工作正常:如果我在查询字符串中传递&isAwesome=true
,参数将使用值true
初始化
我的问题是,我希望将&isAwesome=true
和&isAwesome=1
都接受为true
值。目前,第二个版本将导致输入模型中的IsAwesome
为false
在阅读了关于这个主题的各种博客文章后,我尝试定义一个
HttpParameterBinding
:
public class BooleanNumericParameterBinding : HttpParameterBinding
{
private static readonly HashSet<string> TrueValues =
new HashSet<string>(new[] { "true", "1" }, StringComparer.InvariantCultureIgnoreCase);
public BooleanNumericParameterBinding(HttpParameterDescriptor descriptor) : base(descriptor)
{
}
public override Task ExecuteBindingAsync(
ModelMetadataProvider metadataProvider,
HttpActionContext actionContext,
CancellationToken cancellationToken)
{
var routeValues = actionContext.ControllerContext.RouteData.Values;
var value = (routeValues[Descriptor.ParameterName] ?? 0).ToString();
return Task.FromResult(TrueValues.Contains(value));
}
}
及
这些都不起作用。我的自定义HttpParameterBinding
没有被调用,我仍然将值1
转换为false
如何配置WebAPI以接受布尔值的值1
为true
编辑:我给出的示例是有意简化的。我的应用程序中有很多输入模型,它们包含许多布尔字段,我希望以上述方式处理这些字段。如果只有这一个字段,我就不会求助于如此复杂的机制。看起来用
FromUriAttribute
修饰参数完全跳过了参数绑定规则。我做了一个简单的测试,用一个简单的bool
替换了SampleInput
输入参数:
public string Get([FromUri] bool IsAwesome)
{
//do stuff with the input...
return "ok";
}
而且布尔规则仍然没有被调用(IsAwesome
在调用&IsAwesome=1
时显示为null
)。
一旦删除FromUri属性:
public string Get(bool IsAwesome)
{
//do stuff with the input...
return "ok";
}
将调用规则并正确绑定参数。
FromUriAttribute类是密封的,所以我认为您已经被搞砸了-好吧,您总是可以重新实现它,并包含可选的布尔绑定逻辑。我有一个解决方法建议,在
SampleInput
中创建一个只读属性,比如IsAwesome1
,并将IsAwesome
设为字符串,仅当IsAwesome1
==“1”
或“true”
@ArindamNayak时,才将IsAwesome1
=设置为true。与我的示例中的字段类似,字段太多,会导致代码膨胀。我认为有一种更优雅的方式可以在WebAPI中实现。我现在回到MVC;我有一个IModelBinder
做得很好。
public string Get([FromUri] bool IsAwesome)
{
//do stuff with the input...
return "ok";
}
public string Get(bool IsAwesome)
{
//do stuff with the input...
return "ok";
}