tbf/RestClient/BaseClient.cs
2021-04-03 00:54:18 +02:00

196 lines
7.2 KiB
C#

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace RestClient
{
public class BaseClient
{
private string _baseUrl;
public string ErrorMessage { get; set; }
private AuthenticationHeaderValue _authValue;
public BaseClient(string baseUrl)
{
this._baseUrl = baseUrl;
}
public void SetToken(string token)
{
_authValue = new AuthenticationHeaderValue("Bearer", token);
}
protected Uri GetUrl(string relativeUrl)
{
try
{
return new Uri(_baseUrl + relativeUrl);
}
catch (Exception)
{
Trace.TraceError("Invalid url " + relativeUrl);
return null;
}
}
protected async Task<TResult> GetResultAsync<TResult>(string relativeUrl)
{
ErrorMessage = String.Empty;
Uri url = null;
try
{
url = new Uri(_baseUrl + relativeUrl);
}
catch (Exception)
{
Trace.TraceError("Invalid url " + relativeUrl);
return default(TResult);
}
using (var client = GetClient())
{
try
{
var result = await client.GetAsync(url).ConfigureAwait(false);
var parsedResult = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
if (result.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<TResult>(parsedResult);
}
if (result.StatusCode == System.Net.HttpStatusCode.NotFound)
{
//Create not an error message, because communication is okay, only the meter is not available in database.
return default(TResult);
}
try
{
string Messages = await result.Content.ReadAsStringAsync();
var errors = JsonConvert.DeserializeObject<Dictionary<string, object>>(Messages);
string ServiceError = String.Empty;
if (errors != null)
{
ServiceError = errors["Message"].ToString();
}
ErrorMessage = string.Format("Error message: {0}", ServiceError);
}
catch
{
result.EnsureSuccessStatusCode();
}
return default(TResult);
}
catch (Exception ex)
{
string Message = ex.Message;
if (ex.InnerException != null)
{
Message += ". " + ex.InnerException.Message;
}
Trace.TraceError(Message);
ErrorMessage = Message;
return default(TResult);
}
}
}
/// <summary>
/// Post method.
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="relativeUrl"></param>
/// <param name="Position"></param>
/// /// <param name="withBaseUrl"></param>
/// <returns>The new resource</returns>
protected async Task<string> PostWithReturnDataAsync<TResult>(string relativeUrl, bool withBaseUrl, TResult Position)
{
string data = string.Empty;
ErrorMessage = String.Empty;
Uri url = null;
try
{
if (withBaseUrl)
{
url = new Uri(_baseUrl + relativeUrl);
}
else
{
url = new Uri(relativeUrl);
}
}
catch (Exception ex)
{
Trace.TraceError("Invalid url " + url);
ErrorMessage = ex.Message;
return data;
}
using (var client = GetClient())
{
try
{
string json = JsonConvert.SerializeObject(Position);
HttpContent content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url.ToString(), content).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
data = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return data;
}
else
{
if (response.StatusCode == HttpStatusCode.NotFound)
{
ErrorMessage = String.Format("Status code: {0}. Url: {1}", response.StatusCode, url);
}
else
{
string errorMessageService = string.Empty;
string message = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
if (string.IsNullOrEmpty(message))
{
errorMessageService = response.ReasonPhrase;
}
else
{
try
{
var errors = JsonConvert.DeserializeObject<Dictionary<string, object>>(message);
errorMessageService = errors["Message"].ToString();
}
catch (Exception)
{
errorMessageService = message;
}
}
ErrorMessage = String.Format("Status code: {0}. Error message: {1}", response.StatusCode, errorMessageService);
}
return data;
}
}
catch (Exception ex)
{
Trace.TraceError(ex.Message);
ErrorMessage = ex.Message;
return data;
}
}
}
protected HttpClient GetClient()
{
HttpClientHandler handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
HttpClient client = new HttpClient(handler);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = _authValue;
return client;
}
}
}