'Generic PostAsync method in C#

I'm trying to create a method that will make PostAsync calls to my API. How do I define it so that it can receive one type of object and return another. When I define it with T, it's assuming the parameter and output are of the same kind.

public async Task<T> PostAsync<T>(string url, T param)
{
   HttpContent content = new StringContent(JsonConvert.SerializeObject(param), Encoding.UTF8);
   content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

   var response = await _client.PostAsync(url, content);
   if (!response.IsSuccessStatusCode)
       throw new Exception();

   json = await response.Content.ReadAsStringAsync();

   return JsonConvert.DeserializeObject<T>(json);
}

I call this method and send DomainObjectA and expect to receive a DomainObjectB:

var myObjectA = new DomainObjectA
{
   FirstName = "John",
   LastName = "Doe"
};
var myObjectB = await PostAsync<DomainObjectB>("https://example.com/api/dosomething", myObjectA);

How do I specify both the parameter and the output object types?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source