与counterpart MVC question一致,有没有办法在ASP.NET Web API中为泛型类型创建模型绑定器?
如果是,那么如何在绑定器中处理类型检查和实例化? 假设模型绑定器用于URL参数,请考虑
[ModelBinder(typeof(MyTypeModelBinder))]
public class MyType<T>
{
//...
}
并且
public class MyTypeModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
// check if type if valid? Something like this...
if (!(bindingContext.ModelType.IsGenericType && bindingContext.ModelType.GetGenericTypeDefinition() == typeof(MyType<>)))
{
return false;
}
// create instance...using Activator?
}
}