Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API parameters binding

I have this action in Web Api controller:

public Data GetData(ComplexModel model)

and model is

class ComplexModel
{
     Guid Guid1 { get; set;}
     Guid Guid2 { get; set;}
     string String1 { get; set;}
}

i would like to specify custom binder for Guid type such as empty string or null would bind to empty guid and would like not use nullable type. Was trying to register model binder like this:

var pb = configuration.ParameterBindingRules;
pb.Insert(0, typeof(Guid), param => param.BindWithModelBinding(new GuidBinder())); 

but it is not called and I am getting invalid model state with error message that empty string cant be converted to type Guid.

like image 892
petrov.alex Avatar asked Jan 19 '26 12:01

petrov.alex


1 Answers

Remember, ParameterBindingRules checks the controller action parameter itself (ComplexModel in your case), not the contents of the parameter. You'd need to register a parameter binding against ComplexModel and do any processing with the custom binder to validate the model instance. Seems like you're better off making the Guid properties nullable despite your reluctance to do so.

like image 107
Sixto Saez Avatar answered Jan 21 '26 07:01

Sixto Saez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!