Skip to content

Commit

Permalink
Merge pull request #92 from dragonfruitnetwork/response-disposal-over…
Browse files Browse the repository at this point in the history
…ride

add dispose override for To<T> extension
  • Loading branch information
aspriddell authored Nov 16, 2021
2 parents 80c2915 + 3f86eb2 commit 4e52747
Showing 1 changed file with 20 additions and 10 deletions.
30 changes: 20 additions & 10 deletions DragonFruit.Common.Data/Extensions/ResponseExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,30 @@ namespace DragonFruit.Common.Data.Extensions
{
public static class ResponseExtensions
{
public static T To<T>(this HttpResponseMessage response)
public static T To<T>(this HttpResponseMessage response, bool disposeResponse = true)
{
response.EnsureSuccessStatusCode();
try
{
response.EnsureSuccessStatusCode();

var targetType = typeof(T);
var targetType = typeof(T);

switch (targetType.IsPrimitive)
{
case true:
case false when targetType == typeof(string):
return (T)Convert.ChangeType(response.Content.ReadAsStringAsync().Result, targetType);
switch (targetType.IsPrimitive)
{
case true:
case false when targetType == typeof(string):
return (T)Convert.ChangeType(response.Content.ReadAsStringAsync().Result, targetType);

default:
throw new ArgumentException($"Cannot convert HTTP response to {targetType}. It must be a primitive type or a string", nameof(T));
default:
throw new ArgumentException($"Cannot convert HTTP response to {targetType}. It must be a primitive type or a string", nameof(T));
}
}
finally
{
if (disposeResponse)
{
response.Dispose();
}
}
}
}
Expand Down

0 comments on commit 4e52747

Please sign in to comment.