Created
February 11, 2020 01:32
-
-
Save JerryNixon/8093751cff1c9a1de8e542feba6bcf64 to your computer and use it in GitHub Desktop.
This is handy when writing .NET functions in Azure.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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