laatzen/LaaProductionWeb/LaaProductionWeb.Services/HttpService.cs
2023-05-03 08:21:21 +02:00

81 lines
2.6 KiB
C#

namespace LaaProductionWeb.Services
{
using LaaProductionWeb.Services.Interfaces;
using LaaProductionWeb.Services.Models;
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class HttpService : IHttpService
{
private readonly HttpClient httpClient;
public HttpService(string url)
=> this.httpClient = new HttpClient
{
BaseAddress = new Uri(url, UriKind.Absolute)
};
public async Task<HttpResponseModel> GetAsync(string path)
{
var httpResponseModel = new HttpResponseModel();
try
{
using (var httpRequestMessage = new HttpRequestMessage())
{
httpRequestMessage.Method = HttpMethod.Get;
httpRequestMessage.RequestUri = new Uri(path, UriKind.Relative);
using (var httpResponseMessage = await this.httpClient.SendAsync(httpRequestMessage))
{
httpResponseModel.Succeeded = httpResponseMessage.IsSuccessStatusCode;
if (httpResponseMessage.Content != null)
{
httpResponseModel.Content = await httpResponseMessage.Content?.ReadAsStringAsync();
}
}
}
}
catch (Exception e)
{
httpResponseModel.Error = e.Message;
}
return httpResponseModel;
}
public async Task<HttpResponseModel> OptionsAsync(string path)
{
var httpResponseModel = new HttpResponseModel();
try
{
using (var httpRequestMessage = new HttpRequestMessage())
{
httpRequestMessage.Method = HttpMethod.Options;
httpRequestMessage.RequestUri = new Uri(path, UriKind.Relative);
using (var httpResponseMessage = await this.httpClient.SendAsync(httpRequestMessage))
{
httpResponseModel.Succeeded = httpResponseMessage.IsSuccessStatusCode;
if (httpResponseMessage.Content != null)
{
httpResponseModel.Content = await httpResponseMessage.Content?.ReadAsStringAsync();
}
}
}
}
catch (Exception e)
{
httpResponseModel.Error = e.Message;
}
return httpResponseModel;
}
}
}