Created
May 17, 2018 18:20
-
-
Save jsquire/d50fdd9ecc7cee996271fcdb47ff8732 to your computer and use it in GitHub Desktop.
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
using System; | |
using System.Net.Http; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace SomeApp.Infrastructure | |
{ | |
/// <summary> | |
/// The set of extension methods for the <see cref="HttpRequestMessage" /> | |
/// class. | |
/// </summary> | |
/// | |
public static class HttpRequestMessageExtensions | |
{ | |
/// <summary> | |
/// Reads the content of a request as a string. | |
/// </summary> | |
/// | |
/// <param name="request">The request to read the content of.</param> | |
/// | |
/// <returns>The content of the request, if any; otherwise an empty string.</returns> | |
/// | |
/// <remarks> | |
/// It is safe to call this method multiple times on the same request; content will be read and returned | |
/// for each call. | |
/// </remarks> | |
/// | |
public static async Task<string> ReadContentAsStringAsync(this HttpRequestMessage request) | |
{ | |
if ((request == null) || (request.Content == null)) | |
{ | |
return String.Empty; | |
} | |
var contentBytes = await request.Content.ReadAsByteArrayAsync(); | |
if ((contentBytes == null) || (contentBytes.Length == 0)) | |
{ | |
return String.Empty; | |
} | |
return Encoding.UTF8.GetString(contentBytes); | |
} | |
/// <summary> | |
/// Reads the content of a request as a string, substituting a known value in place of | |
/// any exception that should occur. | |
/// </summary> | |
/// | |
/// <param name="request">The request to read the content of.</param> | |
/// | |
/// <returns>The content of the request, if any; otherwise an empty string. If an exception was encountered during the operation, the <paramref name="errorValue"/> will be returned.</returns> | |
/// | |
/// <remarks> | |
/// It is safe to call this method multiple times on the same request; content will be read and returned | |
/// for each call. | |
/// </remarks> | |
/// | |
public static async Task<string> SafeReadContentAsStringAsync(this HttpRequestMessage request, string errorValue = "{ ERROR READING CONTENT }") | |
{ | |
try | |
{ | |
return await request.ReadContentAsStringAsync(); | |
} | |
catch | |
{ | |
return errorValue; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment