laatzen/LaaProductionWeb/LaaProduction.Http/HttpClient.cs
2024-02-20 14:56:42 +01:00

97 lines
3.5 KiB
C#

namespace LaaProduction.Http
{
using LaaProduction.Http.Interfaces;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
public class HttpClient : IHttpClient
{
private readonly System.Net.Http.HttpClient httpClient;
private readonly string routePrefix;
public HttpClient(string baseURI, string routePrefix)
{
var httpHandler = new HttpClientHandler
{
UseDefaultCredentials = true,
};
this.httpClient = new System.Net.Http.HttpClient(httpHandler)
{
BaseAddress = new Uri(baseURI, UriKind.Absolute)
};
this.routePrefix = routePrefix.TrimEnd('/');
}
public static IHttpClient CreateHttpClient(string baseURI, string routePrefix)
=> new HttpClient(baseURI, routePrefix);
public IHttpMessage Delete(string route, bool full = false)
=> new HttpMessage(this, HttpMethod.Delete, this.Route(route, full));
public IHttpMessage Get(string route, bool full = false)
=> new HttpMessage(this, HttpMethod.Get, this.Route(route, full));
public IHttpMessage Options(string route, bool full = false)
=> new HttpMessage(this, HttpMethod.Options, this.Route(route, full));
public IHttpMessage Post(string route, bool full = false)
=> new HttpMessage(this, HttpMethod.Post, this.Route(route, full));
public IHttpMessage Put(string route, bool full = false)
=> new HttpMessage(this, HttpMethod.Put, this.Route(route, full));
internal async Task<IHttpResponse<T>> SendAsync<T>(HttpMessage fluentHttpRequestMessage)
{
var httpResult = new HttpResponse<T>();
using (fluentHttpRequestMessage)
{
using (var httpResponseMessage = await this.httpClient.SendAsync(fluentHttpRequestMessage))
{
if (httpResponseMessage.Content is HttpContent httpContent)
{
var contentString = await httpContent.ReadAsStringAsync();
try
{
if (httpResponseMessage.IsSuccessStatusCode)
{
httpResult.Value = JsonConvert.DeserializeObject<T>(contentString);
httpResult.Succeeded = httpResponseMessage.IsSuccessStatusCode && httpResult != null;
}
else
{
httpResult.Errors = JsonConvert.DeserializeObject<IDictionary<string, string>>(contentString);
}
}
catch (Exception e)
{
httpResult.Succeeded = false;
httpResult.Message = JsonConvert.SerializeObject(new
{
HttpContent = contentString,
Exception = e.ToString(),
InnerException = e.InnerException?.ToString()
});
}
}
}
}
return httpResult;
}
private string Route(string route, bool full)
{
return full ? route : $"{routePrefix}/{route.TrimStart('/')}";
}
}
}