通用类型的ASP.NET Web API模型绑定器

zam*_*6ak 5 c# asp.net model-binding asp.net-web-api

对应的MVC问题一致,是否有一种方法可以为ASP.NET Web API中的泛型类型创建模型绑定程序?

如果是,如何处理绑定器中的类型检查和实例化?假设模型资料夹是用于URL参数的,请考虑

[ModelBinder(typeof(MyTypeModelBinder))]
public class MyType<T>
{
//...
}
Run Code Online (Sandbox Code Playgroud)

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?
}

}
Run Code Online (Sandbox Code Playgroud)