title: Generic Web Api method
body: <p>I've some classes like <code>CustomerModel</code> or <code>CustomerDetailsModel</code> which are inherting from <code>ModelBase</code>.</p>
  
  <p>Also i don't want to introduce subclasses for each modeltype.</p>
  
  <p>In one case have a post method foreach.</p>
  
  <p>So i could manually create multiple routes to call a method which looks like</p>
  
  <pre><code>Handle&lt;T&gt;(T model) where T : ModelBase
  </code></pre>
  
  <p>They only differ in the path the were called. For example:</p>
  
  <pre><code>baseurl/api/customer =&gt; CustomerModel
  baseurl/api/customerdetails =&gt; CustomerDetailsModel
  </code></pre>
  
  <p>I want to implement a generic web api method like</p>
  
  <pre><code>[HttpPost]
  void Post&lt;T&gt;(T model) where T : ModelBase
  </code></pre>
  
  <p>If I simply create a generic method i got an exception which tells me that the web api method could not have generic methods. But sometime ago I've seen an implementation with web api v1 using some kind of custom lookup mechanisms to handle this. But i can't figure out it anymore.</p>
  
  <p>As a workaround I created a callwrapper which determines the type and invokes a internal generic method, but this feels quite ugly</p>
  
  <pre><code> public async Task&lt;IHttpActionResult&gt; Post(string id, string moduleType)
          {
              await AsyncGenericCallWrapper(moduleType);
  ...
  </code></pre>
  
  <p>It would be much butter to have  the above mentioned generic controllerr.</p>
  
  <pre><code>  private async Task AsyncGenericCallWrapper(string moduleType)
          {
              Type type = GetModuleType(moduleType);
              var content = await Request.Content.ReadAsStringAsync();
              var instance = JsonConvert.DeserializeObject(content, type);
  
              MethodInfo method = this.GetType().GetMethod("InternalGenericMethod", BindingFlags.NonPublic | BindingFlags.Instance);
              MethodInfo generic = method.MakeGenericMethod(type);
              var result = generic.Invoke(this, new object[] { instance }) as Task;
  
              await result;
          }
  </code></pre>
  
  <p>I can image to have a custom Attribute which maps the types like</p>
  
  <pre><code>[GenericRoute("/customer", typeof(CustomerModel)]
  [GenericRoute("/customerDetail", typeof(CustomerDetailModel)]
  void Post&lt;T&gt;(T model) where T : ModelBase
  </code></pre>
  
  <p>With this i could create routes for each attribute, but still the method now get invoked as it is generic , nor i know how to interfer the deserialization mechanism</p>
  
  <p>Can anyone tell me how to implement that GenericWebAPiMethod?</p>