ASP.NET for web API for generic type

According to the MVC mapping question, is there a way to create model bindings for generic types in the ASP.NET Web API?

If so, how would I handle type checking and instantiation in the binder? Suppose model binding refers to URL parameters, consider that 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? } } 
+4
source share

Source: https://habr.com/ru/post/1439938/


All Articles