Sunday 15 January 2012

c# - Custom Boolean Parameter Binding -



c# - Custom Boolean Parameter Binding -

i have webapi method, one:

public string get([fromuri] sampleinput input) { //do stuff input... homecoming "ok"; }

the input defined this:

public class sampleinput { // ...other fields public bool isawesome { get; set; } }

as is, works ok: if pass &isawesome=true in query string, parameter initializes value true.

my problem i'd take both &isawesome=true , &isawesome=1 true values. currently, sec version result in isawesome beingness false in input model.

what tried, after reading various blog posts on subject, define 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(); homecoming task.fromresult(truevalues.contains(value)); } }

... , register in global.asax.cs, using:

var pb = globalconfiguration.configuration.parameterbindingrules; pb.add(typeof(bool), p => new booleannumericparameterbinding(p));

and

var pb = globalconfiguration.configuration.parameterbindingrules; pb.insert(0, typeof(bool), p => new booleannumericparameterbinding(p));

none of these worked. custom httpparameterbinding not beingness called , still value 1 translated false.

how can configure webapi take value 1 true booleans?

edit: illustration presented intentionally simplified. have lot of input models in application , contain many boolean fields handled in manner described above. if there 1 field, not have resorted such complex mechanisms.

looks decorating parameter fromuriattribute skips parameter binding rules altogether. made simple test replacing sampleinput input parameter simple bool:

public string get([fromuri] bool isawesome) { //do stuff input... homecoming "ok"; }

and boolean rule still not getting called (isawesome coming null when phone call &isawesome=1). remove fromuri attribute:

public string get(bool isawesome) { //do stuff input... homecoming "ok"; }

the rule gets called , parameter correctly bound. fromuriattribute class sealed, think you're pretty much screwed - well, can reimplement , include alternate boolean binding logic ^_^.

c# model-binding asp.net-web-api2

No comments:

Post a Comment