自定义布尔参数绑定

Cri*_*scu 10 c# model-binding asp.net-web-api2

我有一个WebApi方法,像这样:

public string Get([FromUri] SampleInput input)
{
    //do stuff with the input...
    return "ok";
}
Run Code Online (Sandbox Code Playgroud)

输入定义如下:

public class SampleInput
{
    // ...other fields
    public bool IsAwesome { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

实际上,它可以正常工作:如果我传入&isAwesome=true查询字符串,则参数将使用值进行初始化true.

我的问题是,我想接受这两个 &isAwesome=true&isAwesome=1作为true价值观.目前,第二个版本将导致IsAwesomefalse输入模型.


在阅读有关该主题的各种博客文章之后,我尝试的是定义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));
    }
}
Run Code Online (Sandbox Code Playgroud)

...并在Global.asax.cs中注册,使用:

var pb = GlobalConfiguration.Configuration.ParameterBindingRules;
pb.Add(typeof(bool), p => new BooleanNumericParameterBinding(p));
Run Code Online (Sandbox Code Playgroud)

var pb = GlobalConfiguration.Configuration.ParameterBindingRules;
pb.Insert(0, typeof(bool), p => new BooleanNumericParameterBinding(p));
Run Code Online (Sandbox Code Playgroud)

这些都没有奏效.我的自定义HttpParameterBinding没有被调用,我仍然将值1转换为false.

如何配置的WebAPI接受该值1作为true对布尔?

编辑:我提出的例子是有意简化的.我的应用程序中有很多输入模型,它们包含许多布尔字段,我希望以上述方式处理它们.如果只有这一个领域,我就不会采用这种复杂的机制.

小智 5

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

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

并且布尔规则仍然没有被调用(IsAwesome就像null你打电话时一样&isAwesome=1)。删除 FromUri 属性后:

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

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