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

时间:2012-10-15 23:13:51

标签: c# asp.net asp.net-web-api model-binding

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

}

0 个答案:

没有答案
相关问题