Is it possible to have a generic method in a controller? I'm talking about something like this:
[HttpPost]
public void DoSomething<T>([FromBody] SomeGenericClass<T> someGenericObject)
{
SomePrivateMethod<T>(someGenericObject);
}
I have actually tried the above (though with different names for everything) and posted to Api/<controllername>/DoSomething
with the instance of someGenericObject<T>
in the request body, and it didn't work (i.e. it didn't reach the controller).
I'm guessing that Web API routing is not able to resolve generic methods since they may result in different methods for different types underneath. But that's just what I think.
So, is it possible to have a generic method in a controller?
Not really. You need to use reflection, basically. Generics are really aimed at static typing rather than types only known at execution time.
But the framework is very extensible and if you get a very good understanding of Routing and Action Selection in ASP.NET Web API and learn how routing, controller selection, action selection, parameter binding and action invocation work, then you can implement some customization for the framework to support generic ...
A generic method may be overloaded like any other method. A class can provide two or more generic methods that specify the same method name but different method parameters.
Generics allow you to define the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.
"Sort of" is the answer here. With generics, you must eventually define the underlying type somewhere and at some point or else it's all just theoretical. How would Web API or MVC route the data in your request (which is just QueryString GET or FormData POST key-value pairs) to a generic type and automatically infer the intended type? It cannot. What you could do is make a private generic method on the controller, but have the Action Methods of the controller resolve to concrete types which are passed to the private generic method.
You could also take a look at this SO answer as an alternative, convention-based approach. It should work pretty well for you assuming that you are specifying the concrete type of your generic controller as part of the URL, QueryString, or FormData.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With