DigitalData.Core/DigitalData.Core.Client/BaseHttpClientService.cs
Developer 02 ba94f4689a feat: Implementierung von BaseHttpClientService und DIExtensions für HTTP-Client-Dienste
- Hinzugefügt: `BaseHttpClientService` zur Handhabung von HTTP-Anfragen mit Cookie-Verwaltung.
- Implementiert: `HttpClientService<TClientOptions>`, das `BaseHttpClientService` für typisierte Client-Optionen erweitert.
- Erstellt: `DIExtensions` zur Registrierung von HTTP-Client-Diensten im Dependency Injection Container.
- Bereitgestellt: Methoden zum Hinzufügen von HTTP-Client-Diensten mit und ohne spezifische Client-Optionen.
- Konfiguriert: Optionen zum Festlegen der Basis-URI für HTTP-Clients.
2024-06-26 13:38:08 +02:00

67 lines
2.3 KiB
C#

using DigitalData.Core.Abstractions.Client;
using Microsoft.Extensions.Options;
using System.Diagnostics.CodeAnalysis;
using System.Net;
namespace DigitalData.Core.Client
{
public class BaseHttpClientService : IBaseHttpClientService
{
protected readonly HttpClient _client;
protected readonly CookieContainer _cookies;
[StringSyntax("Uri")]
public string Uri { get; init; }
public BaseHttpClientService(HttpClient client, CookieContainer cookieContainer, IOptions<HttpClientOptions> clientOptions)
{
_client = client;
_cookies = cookieContainer;
Uri = clientOptions.Value.Uri;
}
public async Task<HttpResponseMessage> FetchAsync(
string route = "",
HttpMethod? method = null,
HttpContent? body = null,
Dictionary<string, string>? form = null,
bool sendWithCookie = true,
bool saveCookie = true
)
{
// set default HTTP method as GET
method ??= HttpMethod.Get;
// create URL
var requestUriStr = Uri + route;
var requestUri = new Uri(requestUriStr);
var requestMessage = new HttpRequestMessage(method, requestUriStr);
// Add cookie to request
if (sendWithCookie)
{
var cookieHeader = _cookies.GetCookieHeader(requestUri);
requestMessage.Headers.Add("Cookie", cookieHeader);
}
// Add body content if provided
if (body != null && form != null)
throw new InvalidOperationException("Body content and form data cannot both be set.");
else if (body != null)
requestMessage.Content = body;
else if (form != null)
requestMessage.Content = new FormUrlEncodedContent(form);
var response = await _client.SendAsync(requestMessage);
// Add response cookies to cookies
if (saveCookie)
if (response.Headers.TryGetValues("Set-Cookie", out var cookies))
foreach (var cookie in cookies)
_cookies.SetCookies(requestUri, cookie);
return response;
}
}
}