【发布时间】:2014-12-09 00:14:58
【问题描述】:
我有一个 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 没有被调用,我仍然将值 1 转换为 false。
如何将 WebAPI 配置为接受值 1 作为布尔值的 true?
编辑:我提供的示例是有意简化的。我的应用程序中有很多输入模型,它们包含许多我希望以上述方式处理的布尔字段。如果只有这一个领域,我就不会使用这么复杂的机制了。
【问题讨论】:
-
我有一个解决方法建议,在
SampleInput中创建一个只读属性IsAwesome1并将IsAwesome设为字符串,设置IsAwesome1= true 仅当IsAwesome="1"或"true" -
@ArindamNayak 像我的示例中那样的字段太多了,这会使代码膨胀。我认为在 Web API 中有一种更优雅的方式来做到这一点。我暂时恢复到 MVC;我有一个
IModelBinder做得很好`。
标签: c# model-binding asp.net-web-api2