12

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?

  • If yes, how?
  • If not, why?
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Gigi
  • 28,163
  • 29
  • 106
  • 188
  • possible duplicate of [In asp.net mvc is it possible to make a generic controller?](http://stackoverflow.com/questions/848904/in-asp-net-mvc-is-it-possible-to-make-a-generic-controller) – phuzi Apr 29 '14 at 14:21

1 Answers1

13

"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.

Community
  • 1
  • 1
Haney
  • 32,775
  • 8
  • 59
  • 68
  • 1
    Your first suggestion is what I originally had in mind, but I wanted to see whether generic controller methods were actually possible. I thought Web API could just use the name of the method but I understand that it actually matches the querystring/body data to the parameters as well, and that's impossible with generics. – Gigi Apr 29 '14 at 14:25
  • 2
    @Gigi not impossible. It just requires you to specify the concrete type in some fashion and interpret it. A custom controller factory looking for the concrete type as part of the URL, QueryString, or FormData would work, though feels a little "hacky" to me. – Haney Apr 29 '14 at 14:26
  • 1
    Yes, it's overkill for what I need. I can just specify a method per type, and use generics internally. – Gigi Apr 29 '14 at 14:27