用于generics类型的ASP.NET Web API模型绑定器
与对应的MVC问题一致 ,有没有办法在ASP.NET Web API中为generics类型创建模型绑定器?
如果是,那么如何在绑定器中处理类型检查和实例化? 假设模型绑定器用于URL参数,请考虑一下
[ModelBinder(typeof(MyTypeModelBinder))] public class MyType { //... }
和
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? } }