Erweiterungsmethoden für HttpResponseMessage hinzugefügt, um JSON und dynamische Antworten zu verarbeiten. Fetch-Methode implementiert, um HTTP-GET-Anfragen auszuführen. ThenAsync für Task-Fortsetzungen und ForEach für IEnumerable-Iteration hinzugefügt.
This commit is contained in:
59
DigitalData.Core.Client/HttpExtensions.cs
Normal file
59
DigitalData.Core.Client/HttpExtensions.cs
Normal file
@@ -0,0 +1,59 @@
|
||||
using Newtonsoft.Json;
|
||||
using System.Net.Http.Json;
|
||||
using static System.Net.WebRequestMethods;
|
||||
|
||||
namespace DigitalData.Core.Client
|
||||
{
|
||||
public static class HttpExtensions
|
||||
{
|
||||
public static async Task<string> Text(this HttpResponseMessage response) => await response.Content.ReadAsStringAsync();
|
||||
|
||||
public static async Task<T?> Json<T>(this HttpResponseMessage response) => await response.Content.ReadFromJsonAsync<T>();
|
||||
|
||||
public static async Task<dynamic> Json(this HttpResponseMessage response)
|
||||
{
|
||||
string json = await response.Content.ReadAsStringAsync();
|
||||
return JsonConvert.DeserializeObject<dynamic>(json) ?? string.Empty;
|
||||
}
|
||||
|
||||
public static async Task<IEnumerable<dynamic>> JsonList(this HttpResponseMessage response)
|
||||
{
|
||||
string json = await response.Content.ReadAsStringAsync();
|
||||
return JsonConvert.DeserializeObject<dynamic>(json) ?? string.Empty;
|
||||
}
|
||||
|
||||
public static async Task<HttpResponseMessage> Fetch(this string url, string method = Http.Get)
|
||||
{
|
||||
using HttpClient client = new();
|
||||
return method switch
|
||||
{
|
||||
Http.Get => await client.GetAsync(url),
|
||||
_ => throw new NotImplementedException(nameof(method)),
|
||||
};
|
||||
}
|
||||
|
||||
public static async void ThenAsync<T>(this Task<T> task, Action<T> toDo)
|
||||
{
|
||||
var then = await task;
|
||||
toDo(then);
|
||||
}
|
||||
|
||||
public static async Task<I> ThenAsync<T, I>(this Task<T> task, Func<T, I> toDo)
|
||||
{
|
||||
var then = await task;
|
||||
return toDo(then);
|
||||
}
|
||||
|
||||
public static async Task<I> ThenAsync<T, I>(this Task<T> task, Func<T, Task<I>> toDoAsync)
|
||||
{
|
||||
var then = await task;
|
||||
return await toDoAsync(then);
|
||||
}
|
||||
|
||||
public static void ForEach<T>(this IEnumerable<T> values, Action<T> action)
|
||||
{
|
||||
foreach (var value in values)
|
||||
action(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user