【问题标题】:Custom Boolean Parameter Binding自定义布尔参数绑定
【发布时间】: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


【解决方案1】:

看起来像用FromUriAttribute 装饰参数只是完全跳过了参数绑定规则。我做了一个简单的测试,用简单的bool 替换了SampleInput 输入参数:

public string Get([FromUri] bool IsAwesome)
{
    //do stuff with the input...
    return "ok";
}

并且布尔规则仍未被调用(当您调用&amp;isAwesome=1 时,IsAwesome 将作为null 出现)。 删除 FromUri 属性后:

public string Get(bool IsAwesome)
{
    //do stuff with the input...
    return "ok";
}

规则被调用并且参数被正确绑定。 FromUriAttribute 类是密封的,所以我认为你搞砸了 - 好吧,你总是可以重新实现它并包含你的备用布尔绑定逻辑^_^。

【讨论】:

    猜你喜欢
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多