V13 / 7879e8b5740b
HttpExtensions.cs
Lilith/Core/Extensions/HttpExtensions.cs
Unchanged from the preceding versionCS
using System.Net.Http.Json;
using System.Text.Json;
namespace Lilith.Core.Extensions;
public static class HttpExtensions
{
public static HttpRequestMessage JsonRequest<T>(string url, T body) =>
new(HttpMethod.Post, url) { Content = JsonContent.Create(body) };
public static T? Deserialize<T>(this string json) =>
JsonSerializer.Deserialize<T>(json);
public static async Task<T?> SendJsonAsync<T>(this HttpClient http, HttpRequestMessage request,
CancellationToken ct = default)
{
using var response = await http.SendAsync(request, ct);
response.EnsureSuccessStatusCode();
return JsonSerializer.Deserialize<T>(await response.Content.ReadAsStringAsync(ct));
}
/// <summary>The caller owns the returned document; the request remains caller-owned.</summary>
public static async Task<JsonDocument> SendJsonDocumentAsync(this HttpClient http, HttpRequestMessage request,
CancellationToken ct = default)
{
using var response = await http.SendAsync(request, ct);
response.EnsureSuccessStatusCode();
return JsonDocument.Parse(await response.Content.ReadAsStringAsync(ct));
}
public static async Task<bool> IsReachableAsync(this HttpClient http, string url)
{
try
{
using HttpResponseMessage response = await http.GetAsync(url);
return response.IsSuccessStatusCode;
}
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException)
{
return false;
}
}
}