问题
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?
}
}
来源:https://stackoverflow.com/questions/12905295/asp-net-web-api-model-binder-for-generic-type