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 /// /// Init classe /// /// public RestCallService(string ApiUrl) { apiUrl = ApiUrl;// _configuration.GetValue("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 /// /// Stato server da chiamare x verifiche preliminari stato API REST /// /// /// 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; } /// /// Effettua una generica chiamata ApiRest /// /// URL Api di base /// Richiesta completa /// 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 /// /// Classe logger /// private static Logger Log = LogManager.GetCurrentClassLogger(); #endregion Private Fields #region Private Properties /// /// Conf client RestSharp standard: /// - base URI al sito /// - timeout 1 min /// private RestClientOptions restOptStd { get; set; } = new RestClientOptions(); #endregion Private Properties } }