laatzen/LaaProductionWeb/LaaProduction.Http/HttpClient.cs
2024-02-08 16:30:23 +01:00

92 lines
3.4 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)
=> new HttpMessage(this, HttpMethod.Delete, $"{routePrefix}/{route.TrimStart('/')}");
public IHttpMessage Get(string route)
=> new HttpMessage(this, HttpMethod.Get, $"{routePrefix}/{route.TrimStart('/')}");
public IHttpMessage Options(string route)
=> new HttpMessage(this, HttpMethod.Options, $"{routePrefix}/{route.TrimStart('/')}");
public IHttpMessage Post(string route)
=> new HttpMessage(this, HttpMethod.Post, $"{routePrefix}/{route.TrimStart('/')}");
public IHttpMessage Put(string route)
=> new HttpMessage(this, HttpMethod.Put, $"{routePrefix}/{route.TrimStart('/')}");
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;
}
}
}