additional http extensions

This commit is contained in:
Ryan Peters 2022-03-07 19:55:09 -05:00
parent 0fcef9ca0b
commit 71f00412c1

View File

@ -1,4 +1,6 @@
using System.Net.Http;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
@ -22,6 +24,40 @@ namespace BinaryDad.Extensions
return client.PostAsync(requestUrl, content);
}
/// <summary>
/// Send a PATCH request to the specified Uri as an asynchronous operation.
/// </summary>
/// <param name="client"></param>
/// <param name="requestUrl"></param>
/// <param name="model"></param>
/// <param name="useDataContractJsonSerializer"></param>
/// <returns></returns>
public static Task<HttpResponseMessage> PatchAsJsonAsync(this HttpClient client, string requestUrl, object model, bool useDataContractJsonSerializer = false)
{
var content = new StringContent(model.Serialize(), Encoding.UTF8, "application/json");
return client.PatchAsync(requestUrl, content);
}
/// <summary>
/// Send a PATCH request to the specified Uri as an asynchronous operation.
/// </summary>
/// <param name="client"></param>
/// <param name="requestUri"></param>
/// <param name="content"></param>
/// <returns></returns>
public static Task<HttpResponseMessage> PatchAsync(this HttpClient client, string requestUri, HttpContent content)
{
var method = new HttpMethod("PATCH");
var message = new HttpRequestMessage(method, requestUri)
{
Content = content
};
return client.SendAsync(message);
}
/// <summary>
/// Serialize the HTTP content to type <typeparamref name="TResponse"/> as an asynchronous operation.
/// </summary>
@ -35,5 +71,41 @@ namespace BinaryDad.Extensions
return result.Deserialize<TResponse>();
}
/// <summary>
/// Gets the body of a <see cref="WebResponse"/> as a string
/// </summary>
/// <param name="response"></param>
/// <returns></returns>
public static string GetResponseBody(this WebResponse response)
{
if (response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
return null;
}
/// <summary>
/// Gets the body of a <see cref="WebResponse"/> as a string
/// </summary>
/// <param name="response"></param>
/// <returns></returns>
public static async Task<string> GetResponseBodyAsync(this WebResponse response)
{
if (response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
return await reader.ReadToEndAsync();
}
}
return null;
}
}
}