Skip to content

Instantly share code, notes, and snippets.

@saintbr
Last active February 26, 2018 08:43
Show Gist options
  • Save saintbr/9e105d43405d50ae8d66943dcecf527f to your computer and use it in GitHub Desktop.
Save saintbr/9e105d43405d50ae8d66943dcecf527f to your computer and use it in GitHub Desktop.
HttpContentExtensions.cs
internal static class HttpContentExtensions
{
public static T As<T>(this HttpContent content) where T : class
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(content.ReadAsStringAsync().Result);
}
}
#USAGE
new HttpClient().GetAsync("[ENDPOINT]").Result.Content.As<T>();
@kiquenet
Copy link

real world sample using the extension?

Wrong usage of the HTTPClient class (in .NET)

In .NET, as Simon Timms described in his article, you have to be careful when using the HTTPClient class.
Continuous instantiation and disposal of the HTTPClient object may create a socket exhaustion on your machine and affect performance.
Consider reusing the HTTPClient object throughout your calls for better performance.

https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
https://ankitvijay.net/2016/09/25/dispose-httpclient-or-have-a-static-instance/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment