Web API参数绑定

pet*_*lex 3 asp.net-web-api

我在Web Api控制器中有这个动作:

public Data GetData(ComplexModel model)
Run Code Online (Sandbox Code Playgroud)

和模型是

class ComplexModel
{
     Guid Guid1 { get; set;}
     Guid Guid2 { get; set;}
     string String1 { get; set;}
}
Run Code Online (Sandbox Code Playgroud)

我想为Guid类型指定自定义绑定器,例如空字符串或null将绑定到空guid并且不想使用可空类型.试图注册这样的模型绑定器:

var pb = configuration.ParameterBindingRules;
pb.Insert(0, typeof(Guid), param => param.BindWithModelBinding(new GuidBinder())); 
Run Code Online (Sandbox Code Playgroud)

但它没有被调用,我得到无效的模型状态,错误信息是空字符串不能转换为类型Guid.

Six*_*aez 6

请记住,ParameterBindingRules检查控制器操作参数本身(ComplexModel在您的情况下),而不是参数的内容.您需要注册参数绑定ComplexModel并使用自定义绑定器执行任何处理以验证模型实例.看起来你最好Guid不要让这些属性成为可能,尽管你不愿意这样做.