我有一个 WebApi 方法,比如这个:
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));
}
}
... 并在 Global.asax.cs 中注册它,使用:
var pb = GlobalConfiguration.Configuration.ParameterBindingRules;
pb.Add(typeof(bool), p => new BooleanNumericParameterBinding(p));
和
var pb = GlobalConfiguration.Configuration.ParameterBindingRules;
pb.Insert(0, typeof(bool), p => new BooleanNumericParameterBinding(p));
这些都不起作用。我的自定义 HttpParameterBinding
没有被调用,我仍然得到转换为 false
的值 1
。
如何配置 WebAPI 以接受值 1
作为 bool 值的 true
?
编辑:我提供的示例是有意简化的。我的应用程序中有很多输入模型,它们包含许多我希望以上述方式处理的 bool 字段。如果只有这一个领域,我就不会诉诸如此复杂的机制。
最佳答案
看起来用 FromUriAttribute
装饰参数只是完全跳过了参数绑定(bind)规则。我做了一个简单的测试,用一个简单的 bool
替换了 SampleInput
输入参数:
public string Get([FromUri] bool IsAwesome)
{
//do stuff with the input...
return "ok";
}
并且 bool 规则仍未被调用(当您调用 &isAwesome=1
时,IsAwesome
以 null
的形式出现)。
一旦删除 FromUri 属性:
public string Get(bool IsAwesome)
{
//do stuff with the input...
return "ok";
}
规则被调用并且参数被正确绑定(bind)。 FromUriAttribute 类是密封的,所以我认为您完全搞砸了 - 好吧,您总是可以重新实现它并包含您的备用 bool 绑定(bind)逻辑 ^_^。
关于c# - 自定义 bool 参数绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26356802/