'Templating return types
I'm trying to make this return a templated object which is a different type that what is sent. How do I do it?
UserSSS user = new UserSSS();
ReturnObject foo = await _callServer.PostAsync($"{Constants.SERVER_URL}/profiles/v1/HelloObject", user);
public async Task<T> PostAsync<T>(string url, T toPost)
{
HttpClientHandler httpClientHandler = new HttpClientHandler();
#if DEBUG
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
#endif
string json = JsonConvert.SerializeObject(toPost);
StringContent httpContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (var client = new HttpClient(httpClientHandler))
{
var ret = await client.PostAsync(url, httpContent);
string contents = await ret.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject(contents);
}
}
} ```
Solution 1:[1]
Do you mean different generic input and output types? If yes then it's simple as:
public async Task<TOut> PostAsync<TIn, TOut>(string url, TIn toPost)
and in the return
return JsonConvert.DeserializeObject<TOut>(contents);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | funatparties |
