Skip to content

Instantly share code, notes, and snippets.

@JerryNixon
Created February 11, 2020 01:32
Show Gist options
  • Select an option

  • Save JerryNixon/8093751cff1c9a1de8e542feba6bcf64 to your computer and use it in GitHub Desktop.

Select an option

Save JerryNixon/8093751cff1c9a1de8e542feba6bcf64 to your computer and use it in GitHub Desktop.
This is handy when writing .NET functions in Azure.
public static class HttpRequestExtensions
{
public static bool TryGetBody<T>(this HttpRequest req, out T value, out Exception exception)
{
if (!req.TryGetBody(out var bytes, out exception))
{
value = default;
return false;
}
try
{
var json = BitConverter.ToString(bytes);
value = JsonConvert.DeserializeObject<T>(json);
exception = default;
return true;
}
catch (Exception ex)
{
value = default;
exception = ex;
return false;
}
}
public static bool TryGetBody(this HttpRequest req, out byte[] value, out Exception exception)
{
try
{
if ((req.Body?.Length ?? 0) == 0)
{
throw new Exception("HttpRequest has no body.");
}
value = GetBytes();
exception = default;
return true;
}
catch (Exception ex)
{
value = default;
exception = ex;
return false;
}
byte[] GetBytes()
{
byte[] bytes;
using (var ms = new MemoryStream())
{
req.Body.CopyTo(ms);
bytes = ms.ToArray();
}
return bytes;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment