315 lines
9.5 KiB
C#
315 lines
9.5 KiB
C#
using System;
|
|
using RestSharp;
|
|
using System.Net.Http;
|
|
using System.Threading;
|
|
using xCommons.Constants;
|
|
using xCommons.Extensions;
|
|
using xExceptions.Constants;
|
|
using System.Threading.Tasks;
|
|
using xHttpService.Constants;
|
|
using xIdentityModels.Models;
|
|
using xHttpService.Interfaces;
|
|
using RestSharp.Authenticators;
|
|
using System.Collections.Generic;
|
|
using xHttpService.Configurations;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace xHttpService.Providers {
|
|
public partial class XHttpProvider : IXHttpProvider {
|
|
//
|
|
private readonly ILogger<XHttpProvider> logger;
|
|
private readonly XHttpServiceConfiguration configuration;
|
|
|
|
public XHttpProvider (
|
|
ILogger<XHttpProvider> logger,
|
|
XHttpServiceConfiguration configuration
|
|
)
|
|
{
|
|
this.logger = logger;
|
|
this.configuration = configuration;
|
|
}
|
|
|
|
//
|
|
#region Actions ...
|
|
/// <summary>
|
|
/// Get an Instance of Http Client
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public HttpClient GetHttpClient()
|
|
{
|
|
//
|
|
HttpClient httpClient = null;
|
|
|
|
//
|
|
// httpClient = new HttpClient ();
|
|
var httpClientHandler = new HttpClientHandler()
|
|
{
|
|
ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) =>
|
|
{
|
|
//
|
|
logger.LogInformation(
|
|
$"XSSL Handler: {Environment.NewLine}, sender: {sender}, {Environment.NewLine} cert: {cert}, {Environment.NewLine} chain: {chain}, {Environment.NewLine} sslPolicyErrors: {sslPolicyErrors}"
|
|
);
|
|
|
|
//
|
|
return true;
|
|
},
|
|
ClientCertificateOptions = ClientCertificateOption.Manual,
|
|
};
|
|
httpClient = new HttpClient(httpClientHandler);
|
|
|
|
//
|
|
return httpClient;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Retrieve Rest Client ...
|
|
/// </summary>
|
|
/// <param name="baseUrl"></param>
|
|
/// <param name="tokens"></param>
|
|
/// <returns></returns>
|
|
public RestClient GetRestClient(
|
|
string baseUrl = null,
|
|
XTokenResponse tokens = null
|
|
)
|
|
{
|
|
//
|
|
var client = new RestClient(baseUrl);
|
|
|
|
//
|
|
// Set Authenticator ...
|
|
if (!tokens.IsNull() &&
|
|
!tokens.AccessToken.IsNullOrEmpty())
|
|
{
|
|
client.Authenticator = new JwtAuthenticator(tokens.AccessToken);
|
|
}
|
|
|
|
//
|
|
// Refresh Token ...
|
|
if (!tokens.IsNull() &&
|
|
!tokens.RefreshToken.IsNullOrEmpty())
|
|
{
|
|
client.AddDefaultHeader(XAuthorization.RefreshToken, tokens.RefreshToken);
|
|
}
|
|
|
|
//
|
|
// ExpiresAt ...
|
|
if (!tokens.IsNull() &&
|
|
tokens.ExpiresAt > 0)
|
|
{
|
|
client.AddDefaultHeader(XAuthorization.ExpiresAt, tokens.ExpiresAt.AsHttpParamString());
|
|
}
|
|
|
|
//
|
|
// Set Default Timeout ...
|
|
client.Timeout = configuration.DefaultClientTimeout;
|
|
|
|
//
|
|
// SSL Validation Handler ...
|
|
client.RemoteCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) =>
|
|
{
|
|
//
|
|
logger.LogInformation(
|
|
$"XSSL Handler: {Environment.NewLine}, sender: {sender}, {Environment.NewLine} cert: {cert}, {Environment.NewLine} chain: {chain}, {Environment.NewLine} sslPolicyErrors: {sslPolicyErrors}"
|
|
);
|
|
|
|
//
|
|
return true;
|
|
};
|
|
|
|
//
|
|
return client;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Prepare and Retrieve a Rest Request ...
|
|
/// </summary>
|
|
/// <param name="endpoint"></param>
|
|
/// <param name="poweredValue"></param>
|
|
/// <param name="params"></param>
|
|
/// <param name="headers"></param>
|
|
/// <param name="queryStrings"></param>
|
|
/// <returns></returns>
|
|
public RestRequest GetRestRequet(
|
|
string endpoint,
|
|
string poweredValue = null,
|
|
IDictionary<string, string> @params = null,
|
|
IDictionary<string, string> headers = null,
|
|
IDictionary<string, string> queryStrings = null
|
|
)
|
|
{
|
|
//
|
|
var url = endpoint;
|
|
|
|
//
|
|
// Add Route Payloads ...
|
|
if (!@params.IsNull() && @params.Count > 0)
|
|
{
|
|
//
|
|
var enumerator = @params.GetEnumerator();
|
|
while (enumerator.MoveNext())
|
|
{
|
|
//
|
|
var item = enumerator.Current;
|
|
|
|
//
|
|
url = url.Replace(item.Key, item.Value.ToUrlEncoded());
|
|
}
|
|
}
|
|
|
|
//
|
|
// Add Query Strings ...
|
|
if (!queryStrings.IsNull() && queryStrings.Count > 0)
|
|
{
|
|
//
|
|
url = $"{url}?";
|
|
var enumerator = queryStrings.GetEnumerator();
|
|
while (enumerator.MoveNext())
|
|
{
|
|
//
|
|
var item = enumerator.Current;
|
|
|
|
//
|
|
url += $"{item.Key}={item.Value.ToUrlEncoded()}&";
|
|
}
|
|
|
|
//
|
|
// remove lates & ...
|
|
if (url.EndsWith("&"))
|
|
{
|
|
url = url.Substring(0, url.Length - 1);
|
|
}
|
|
}
|
|
|
|
//
|
|
// Create request ...
|
|
var request = new RestRequest(url, DataFormat.Json);
|
|
|
|
//
|
|
if (!poweredValue.IsNullOrEmpty())
|
|
{
|
|
//
|
|
request.AddHeader(
|
|
XAuthorization.XPoweredBy,
|
|
poweredValue
|
|
);
|
|
}
|
|
|
|
//
|
|
// Add Headers to request ...
|
|
if (!headers.IsNull() && headers.Count > 0)
|
|
{
|
|
//
|
|
var enumerator = headers.GetEnumerator();
|
|
while (enumerator.MoveNext())
|
|
{
|
|
//
|
|
var item = enumerator.Current;
|
|
request.AddHeader(item.Key, item.Value);
|
|
}
|
|
}
|
|
|
|
//
|
|
return request;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Handle Call Specific Request and retrieve Response
|
|
/// </summary>
|
|
/// <param name="client"></param>
|
|
/// <param name="request"></param>
|
|
/// <param name="method"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <typeparam name="T"></typeparam>
|
|
/// <returns></returns>
|
|
public async Task<T> RunRestRequest<T>(
|
|
RestClient client,
|
|
RestRequest request,
|
|
XHttpMethod method,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
var response = await Task.Run(async () =>
|
|
{
|
|
//
|
|
IRestResponse resp = null;
|
|
|
|
//
|
|
// Call Endpoint Service using Specified Method ...
|
|
switch (method)
|
|
{
|
|
//
|
|
// Get ...
|
|
case XHttpMethod.GET:
|
|
resp = client.Get(request);
|
|
break;
|
|
|
|
//
|
|
// Put ...
|
|
case XHttpMethod.PUT:
|
|
resp = client.Put(request);
|
|
break;
|
|
|
|
//
|
|
// Post ...
|
|
case XHttpMethod.POST:
|
|
resp = client.Post(request);
|
|
break;
|
|
|
|
//
|
|
// Delete ...
|
|
case XHttpMethod.DELETE:
|
|
resp = client.Delete(request);
|
|
break;
|
|
}
|
|
|
|
//
|
|
if (!resp.IsSuccessful)
|
|
{
|
|
//
|
|
// Log Exception ...
|
|
logger.LogError($"Error: {resp.ErrorMessage}");
|
|
logger.LogError($"Exception: {resp.ErrorException.ToJSON()}");
|
|
if (!resp.ErrorMessage.IsNullOrEmpty() &&
|
|
resp.ErrorMessage.Contains("timed out"))
|
|
{
|
|
XException.Timeout.Throw();
|
|
}
|
|
|
|
//
|
|
var ex = resp.Content.ToXError();
|
|
if (!ex.IsNull())
|
|
{
|
|
throw ex.ToException();
|
|
}
|
|
|
|
//
|
|
// UnAuthorized ...
|
|
if (resp.StatusCode == System.Net.HttpStatusCode.Unauthorized)
|
|
{
|
|
XException.NotAuthorized.Throw();
|
|
}
|
|
|
|
//
|
|
// NotFound ...
|
|
if (resp.StatusCode == System.Net.HttpStatusCode.NotFound)
|
|
{
|
|
XException.NotFound.Throw();
|
|
}
|
|
|
|
//
|
|
XException.ActionFailed.Throw();
|
|
}
|
|
|
|
//
|
|
var result = resp.Content.FromJSON<T>();
|
|
return result;
|
|
}, cancellationToken);
|
|
|
|
//
|
|
return response;
|
|
}
|
|
#endregion
|
|
}
|
|
} |