ASP.NET Web API Model Binder for Generic Type

2019-06-26 00:59发布

In line with counterpart MVC question, is there a way to create a model binder for generic types in ASP.NET Web API?

If yes, how would one handle type checking and instantiation in the binder? Assume model binder is for URL parameters, consider you have

[ModelBinder(typeof(MyTypeModelBinder))]
public class MyType<T>
{
//...
}

And

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条回答
登录 后发表回答