Files
maat/Maat.Data/Services/RestCallService.cs
Samuele Locatelli 1b9252cb67 Fix file2send x x64
Update x gestioen metodo send Rest (da testare!!!)
2024-10-29 19:19:25 +01:00

125 lines
3.8 KiB
C#

using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Maat.Data.Services
{
public class RestCallService
{
#region Public Constructors
/// <summary>
/// Init classe
/// </summary>
/// <param name="ApiUrl"></param>
public RestCallService(string ApiUrl)
{
apiUrl = ApiUrl;// _configuration.GetValue<string>("SrvConf:Prog.ApiUrl") ?? "http://office.egalware.com/MP/PROG";
// fix opzioni base del RestClient
restOptStd = new RestClientOptions
{
Timeout = TimeSpan.FromSeconds(60),
BaseUrl = new Uri(apiUrl),
ThrowOnAnyError = true,
ThrowOnDeserializationError = true
};
}
private string apiUrl = "";
#endregion Public Constructors
#region Public Methods
/// <summary>
/// Stato server da chiamare x verifiche preliminari stato API REST
/// </summary>
/// <param name="ApiUrl"></param>
/// <returns></returns>
public string CheckServer()
{
string answ = "ND";
// cerco online
using (RestClient client = new RestClient(restOptStd))
{
var request = new RestRequest($"api/health", Method.Get);
try
{
var response = client.ExecuteGet(request);
//var response = await client.GetAsync(request);
// controllo risposta
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
// verifico risposta
if (response.Content != null)
{
answ = response.Content.Replace("\"", "");
//answ= JValue.Parse(response.Content).ToString(Formatting.Indented);
}
}
}
catch (Exception exc)
{
Log.Error($"Eccezione in CheckServer{Environment.NewLine}{exc}");
}
}
return answ;
}
/// <summary>
/// Effettua una generica chiamata ApiRest
/// </summary>
/// <param name="ApiUrl">URL Api di base</param>
/// <param name="ApiRequest">Richiesta completa</param>
/// <returns></returns>
public RestResponse CallRestGet(string ApiUrl, string ApiRequest)
{
RestResponse response;
var currOpt = new RestClientOptions
{
Timeout = TimeSpan.FromSeconds(60),
BaseUrl = new Uri(ApiUrl),
ThrowOnAnyError = true,
ThrowOnDeserializationError = true
};
// cerco online
using (RestClient client = new RestClient(currOpt))
{
var request = new RestRequest(ApiRequest, Method.Get);
response = client.Get(request);
}
return response;
}
#endregion Public Methods
#region Private Fields
/// <summary>
/// Classe logger
/// </summary>
private static Logger Log = LogManager.GetCurrentClassLogger();
#endregion Private Fields
#region Private Properties
/// <summary>
/// Conf client RestSharp standard:
/// - base URI al sito
/// - timeout 1 min
/// </summary>
private RestClientOptions restOptStd { get; set; } = new RestClientOptions();
#endregion Private Properties
}
}