Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use generic methods in a controller?

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?
like image 951
Gigi Avatar asked Apr 29 '14 14:04

Gigi


People also ask

Can dynamic type be used for generic?

Not really. You need to use reflection, basically. Generics are really aimed at static typing rather than types only known at execution time.

How do you implement a generic action in Web API?

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

Can we overload generic methods?

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.

What is a generic method and when should it be used C#?

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.


1 Answers

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

like image 91
Haney Avatar answered Oct 13 '22 20:10

Haney