Skip to content

Commit

Permalink
Handle EmptyContent
Browse files Browse the repository at this point in the history
  • Loading branch information
HugoBurgess committed Oct 25, 2024
1 parent d131701 commit 6bbd7fc
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
6 changes: 3 additions & 3 deletions FileShareClient/Internal/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@ internal static class Extensions
/// <returns></returns>
public static async Task<T> ReadAsTypeAsync<T>(this HttpResponseMessage httpResponseMessage)
{
var bodyJson = await httpResponseMessage.Content.ReadAsStringAsync();
var bodyJson = await httpResponseMessage.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(bodyJson);
}

public static async Task<Stream> ReadAsStreamAsync(this HttpResponseMessage httpResponseMessage)
{
return await httpResponseMessage.Content.ReadAsStreamAsync();
return await httpResponseMessage.Content.ReadAsStreamAsync();
}

/// <summary>
Expand Down Expand Up @@ -54,4 +54,4 @@ public static byte[] CalculateMD5(this Stream stream)
}
}
}
}
}
14 changes: 11 additions & 3 deletions FileShareClient/Models/Result.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,19 @@ public class Result<T> : IResult<T>

internal static class Result
{
/// <summary>
/// Until .NET 5 (and including Framework 4.8), HttpResponseMessage.Content could return null.
/// After .NET 5, HttpResponseMessage.Content will never be null. If set to null then it will return System.Net.Http.EmptyContent, an internal class.
/// </summary>
/// <param name="response"></param>
/// <returns></returns>
private static bool HasContent(this HttpResponseMessage response) => response.Content != null && response.Content.GetType().Name != "EmptyContent";

internal static async Task<IResult<Stream>> WithStreamData(HttpResponseMessage response)
{
Stream data = default;

if (response.IsSuccessStatusCode && response.Content != null)
if (response.IsSuccessStatusCode && response.HasContent())
{
data = await response.ReadAsStreamAsync();
}
Expand All @@ -35,7 +43,7 @@ internal static async Task<IResult<U>> WithObjectData<U>(HttpResponseMessage res
{
U data = default;

if (response.IsSuccessStatusCode && response.Content != null)
if (response.IsSuccessStatusCode && response.HasContent())
{
data = await response.ReadAsTypeAsync<U>();
}
Expand All @@ -59,7 +67,7 @@ private static async Task<IResult<U>> CreateResultAsync<U>(HttpResponseMessage r
Errors = new List<Error>()
};

if (response.Content != null && !response.IsSuccessStatusCode)
if (!response.IsSuccessStatusCode && response.HasContent())
{
try
{
Expand Down

0 comments on commit 6bbd7fc

Please sign in to comment.