-->

Can you use generic methods in a controller?

2020-08-23 08:42发布

问题:

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?

回答1:

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