title: Pass typeof(x) type to generic method
body: <p>I've made some Middleware that logs all actions taken by a user within my application.  Depending on the action taken, I need parse out some [FromBody] JSON into their respective key/value pairs for logging. </p>
  
  <p>I need to deserialize my JSON within the middleware, but in order to do that, I need to send my DtoType along to the deserializer in order for it to parse out my key/values.  I've got a method setup to do that, but I need to pass in a generic type because this will be different for every single action the user takes.  (e.g. I have a UserDto, CustomerDto, etc...)</p>
  
  <p>I've setup a dictionary in order to get the type that I need, however when I pass the var to my logging method to do the rest of the work, I get an error stating that this is not a type but a variable.  This is true, however I have no idea how I'm supposed to get the type that I pulled out of my dictionary into the method generic type.</p>
  
  <p>See my code below:</p>
  
  <p><strong>LoggingMiddleware.cs readonly dictionary</strong></p>
  
  <pre><code>    private readonly Dictionary&lt;string, Type&gt; _postDictionary = new Dictionary&lt;string, Type&gt;
      {
          { "path/customers", typeof(CustomerPostDto) },
          ...//More entries//...
      };
  </code></pre>
  
  <p><strong>LoggingMiddleware.cs Invoke Method</strong></p>
  
  <pre><code>public async Task Invoke(HttpContext context)
  {
      using (var streamCopy = new MemoryStream())
      {
          ...//Do some stuff here//...
          //Logging Actions
          if (request.Path != "/")
          {
              if (request.Method == "POST")
              {
                 Type T = _postDictionary[path];
                 logAction&lt;T&gt;(contextDto);
              }
          }
          ...//Do some stuff here//...
      }
  }
  </code></pre>
  
  <p><strong>LoggingMiddleware.cs logAction Method</strong></p>
  
  <pre><code>private void logAction&lt;T&gt;(object contextDto)
  {
      var dto = ControllerBase.ParseBody&lt;T&gt;(contextDto.Body);
      ...//Do some stuff here//...
  }
  </code></pre>
  
  <p><strong>EDIT: Following Example of Possible Duplicate - updated code</strong></p>
  
  <pre><code>                if (request.Method == "POST")
                  {
                      Type T = _postDictionary[path];
  
                      MethodInfo methodLogAction = typeof(LoggingMiddleware).GetMethod("logAction", BindingFlags.NonPublic);
                      MethodInfo generic = methodLogAction.MakeGenericMethod(T);
                      generic.Invoke(contextDto, null);
                  }
  </code></pre>
  
  <p>The above never returns anything for GetMethod other than null.</p>