DigitalData.Core/DigitalData.Core.Client/BaseHttpClientService.cs

116 lines
4.5 KiB
C#

using DigitalData.Core.Abstractions.Client;
using Microsoft.Extensions.Options;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Web;
namespace DigitalData.Core.Client
{
public class BaseHttpClientService : IBaseHttpClientService
{
protected readonly HttpClient _client;
protected readonly CookieContainer _cookies;
[StringSyntax("Uri")]
public string Uri { get; init; }
public string Path { get; init; } = string.Empty;
public BaseHttpClientService(HttpClient client, CookieContainer cookieContainer, IOptions<HttpClientOptions> clientOptions)
{
_client = client;
_cookies = cookieContainer;
Uri = clientOptions.Value.Uri.Trim(URI_TRIM_CHARS);
Path = clientOptions.Value.Path.Trim(URI_TRIM_CHARS);
}
public CookieCollection GetCookies(string path = "") => _cookies.GetCookies(uri: new Uri(UriCombine(Uri, path, path.Trim(URI_TRIM_CHARS))));
public async Task<HttpResponseMessage> FetchAsync(
string? scheme = null,
int? port = null,
string path = "",
IEnumerable<KeyValuePair<string, object?>>? queryParams = null,
HttpMethod? method = null,
HttpContent? body = null,
IEnumerable<KeyValuePair<string, object>>? form = null,
IEnumerable<KeyValuePair<string, object>>? headers = null,
bool sendWithCookie = true,
bool saveCookie = true
)
{
// set default HTTP method as GET
method ??= HttpMethod.Get;
// create URL
var uriBuilder = new UriBuilder(Uri);
if (scheme is not null)
uriBuilder.Scheme = scheme;
if (port is int portInt)
uriBuilder.Port = portInt;
uriBuilder.Path = UriCombine(Path, path?.Trim(URI_TRIM_CHARS) ?? string.Empty);
// Add query parameters if provided
if (queryParams?.Any() ?? false)
{
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
var flagParams = queryParams.Where(param => param.Value is null).Select(param => HttpUtility.UrlEncode(param.Key));
var valueParams = queryParams.Where(param => param.Value is not null);
foreach (var param in valueParams)
query[param.Key] = param.Value switch
{
bool b => b.ToString().ToLower(),
_ => HttpUtility.UrlEncode(param.Value.ToString())
};
var flagQuery = string.Join(QUERY_SEPARATOR, flagParams);
uriBuilder.Query = string.Join(QUERY_SEPARATOR, query.ToString(), flagQuery);
}
var requestUri = uriBuilder.Uri;
Console.WriteLine(requestUri);
var requestMessage = new HttpRequestMessage(method, requestUri);
// Add headers if provided
headers?.ForEach(header => requestMessage.Headers.Add(header.Key, header.Value.ToString()));
// Add cookie to request
if (sendWithCookie)
{
var cookieHeader = _cookies.GetCookieHeader(requestUri);
if (!string.IsNullOrWhiteSpace(cookieHeader))
{
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.Select(e => KeyValuePair.Create(e.Key, e.Value.ToString())));
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;
}
internal static readonly char[] URI_TRIM_CHARS = { '\\', '/', ' ' };
internal static string UriCombine(params string[] paths) => System.IO.Path.Combine(paths).Replace("\\", "/");
internal static readonly char QUERY_SEPARATOR = '&';
}
}