Compare commits
4
Commits
b22dbb8b0c
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3afe34e438 | ||
|
|
3f707317bf | ||
|
|
f3372333fd | ||
|
|
d412141193 |
@@ -0,0 +1,7 @@
|
|||||||
|
namespace xHttpService.Constants
|
||||||
|
{
|
||||||
|
public struct XSSEConstants
|
||||||
|
{
|
||||||
|
public const string DataIdentifier = "data:";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -132,7 +132,7 @@ namespace xHttpService.Extensions
|
|||||||
/// Add XAccessToken Header to specific RestRequest Headers ...
|
/// Add XAccessToken Header to specific RestRequest Headers ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="source"></param>
|
/// <param name="source"></param>
|
||||||
/// <param name="poweredByValue"></param>
|
/// <param name="token"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public static RestRequest AddXAccessToken(
|
public static RestRequest AddXAccessToken(
|
||||||
this RestRequest source,
|
this RestRequest source,
|
||||||
|
|||||||
@@ -0,0 +1,147 @@
|
|||||||
|
using System;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading;
|
||||||
|
using xCommons.Extensions;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.AspNetCore.Http.Features;
|
||||||
|
|
||||||
|
namespace xHttpService.Extensions
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Server-Sent Events (SSE) Helpers ...
|
||||||
|
/// Format (per Spec): [event: name\n] data: line\n ... \n
|
||||||
|
/// </summary>
|
||||||
|
public static class XSseExtensions
|
||||||
|
{
|
||||||
|
//
|
||||||
|
// Event Names ...
|
||||||
|
public const string SseDoneEvent = "done";
|
||||||
|
public const string SseErrorEvent = "error";
|
||||||
|
public const string SseContentType = "text/event-stream; charset=utf-8";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Configure Response for SSE (Headers + Disable Buffering) ...
|
||||||
|
/// Must be Called before any Write ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="source"></param>
|
||||||
|
public static void PrepareSseResponse(
|
||||||
|
this HttpResponse source
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
if (source.IsNull() || source.HasStarted)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
source.StatusCode = StatusCodes.Status200OK;
|
||||||
|
source.ContentType = SseContentType;
|
||||||
|
source.Headers["Cache-Control"] = "no-cache, no-store";
|
||||||
|
source.Headers["X-Accel-Buffering"] = "no";
|
||||||
|
|
||||||
|
//
|
||||||
|
// Disable Response Buffering ...
|
||||||
|
source.HttpContext.Features
|
||||||
|
.Get<IHttpBufferingFeature>()?
|
||||||
|
.DisableResponseBuffering();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Write an Object as JSON (camelCase) SSE Event ...
|
||||||
|
/// </summary>
|
||||||
|
public static Task WriteSseEventAsync<T>(
|
||||||
|
this HttpResponse source,
|
||||||
|
T data,
|
||||||
|
string eventName = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var payload = data.IsNull()
|
||||||
|
? "null"
|
||||||
|
: data.ToJSON(camelCase: true);
|
||||||
|
|
||||||
|
//
|
||||||
|
return source.WriteSseRawAsync(payload, eventName, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Write Raw Text as SSE Event (Multi Line Text is Split into Multiple data: Lines) ...
|
||||||
|
/// </summary>
|
||||||
|
public static async Task WriteSseRawAsync(
|
||||||
|
this HttpResponse source,
|
||||||
|
string payload,
|
||||||
|
string eventName = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
if (!eventName.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
builder.Append("event: ").Append(eventName).Append('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var normalized = (payload ?? string.Empty)
|
||||||
|
.Replace("\r\n", "\n")
|
||||||
|
.Replace('\r', '\n');
|
||||||
|
foreach (var line in normalized.Split('\n'))
|
||||||
|
{
|
||||||
|
builder.Append("data: ").Append(line).Append('\n');
|
||||||
|
}
|
||||||
|
builder.Append('\n');
|
||||||
|
|
||||||
|
//
|
||||||
|
await source.WriteAsync(builder.ToString(), Encoding.UTF8, cancellationToken);
|
||||||
|
await source.Body.FlushAsync(cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Write Terminating "done" Event ...
|
||||||
|
/// </summary>
|
||||||
|
public static Task WriteSseDoneAsync(
|
||||||
|
this HttpResponse source,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
|
return source.WriteSseRawAsync("[DONE]", SseDoneEvent, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Write "error" Event (Never Throws; Used when Stream has Already Started) ...
|
||||||
|
/// </summary>
|
||||||
|
public static async Task WriteSseErrorAsync(
|
||||||
|
this HttpResponse source,
|
||||||
|
string message
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await source.WriteSseEventAsync(
|
||||||
|
data: new { error = message ?? "Stream Failed" },
|
||||||
|
eventName: SseErrorEvent,
|
||||||
|
cancellationToken: CancellationToken.None
|
||||||
|
);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// Client Gone ...
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Is Exception Caused by Client Disconnect / Cancellation ...
|
||||||
|
/// </summary>
|
||||||
|
public static bool IsClientCancellation(
|
||||||
|
this Exception source,
|
||||||
|
CancellationToken cancellationToken
|
||||||
|
)
|
||||||
|
{
|
||||||
|
return source is OperationCanceledException && cancellationToken.IsCancellationRequested;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,28 +1,63 @@
|
|||||||
using RestSharp;
|
using RestSharp;
|
||||||
using System.Net.Http;
|
using System.Net.Http;
|
||||||
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using xHttpService.Constants;
|
using xHttpService.Constants;
|
||||||
using xIdentityModels.Models;
|
using xIdentityModels.Models;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
|
||||||
namespace xHttpService.Interfaces {
|
namespace xHttpService.Interfaces
|
||||||
public partial interface IXHttpProvider {
|
{
|
||||||
HttpClient GetHttpClient ();
|
public partial interface IXHttpProvider
|
||||||
RestClient GetRestClient (
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Get an Instance of Http Client
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
HttpClient GetHttpClient();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Retrieve Rest Client ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="baseUrl"></param>
|
||||||
|
/// <param name="tokens"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
RestClient GetRestClient(
|
||||||
string baseUrl = null,
|
string baseUrl = null,
|
||||||
string poweredByValue = null,
|
|
||||||
XTokenResponse tokens = null
|
XTokenResponse tokens = null
|
||||||
);
|
);
|
||||||
RestRequest GetRestRequet (
|
|
||||||
|
/// <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>
|
||||||
|
RestRequest GetRestRequet(
|
||||||
string endpoint,
|
string endpoint,
|
||||||
|
string poweredValue = null,
|
||||||
IDictionary<string, string> @params = null,
|
IDictionary<string, string> @params = null,
|
||||||
IDictionary<string, string> headers = null,
|
IDictionary<string, string> headers = null,
|
||||||
IDictionary<string, string> queryStrings = null
|
IDictionary<string, string> queryStrings = null
|
||||||
);
|
);
|
||||||
Task<T> RunRestRequest<T> (
|
|
||||||
|
/// <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>
|
||||||
|
Task<T> RunRestRequest<T>(
|
||||||
RestClient client,
|
RestClient client,
|
||||||
RestRequest request,
|
RestRequest request,
|
||||||
XHttpMethod method
|
XHttpMethod method,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+131
-91
@@ -1,7 +1,7 @@
|
|||||||
using System;
|
using System;
|
||||||
using RestSharp;
|
using RestSharp;
|
||||||
using xModels.Base;
|
|
||||||
using System.Net.Http;
|
using System.Net.Http;
|
||||||
|
using System.Threading;
|
||||||
using xCommons.Constants;
|
using xCommons.Constants;
|
||||||
using xCommons.Extensions;
|
using xCommons.Extensions;
|
||||||
using xExceptions.Constants;
|
using xExceptions.Constants;
|
||||||
@@ -15,14 +15,17 @@ using xHttpService.Configurations;
|
|||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
namespace xHttpService.Providers {
|
namespace xHttpService.Providers {
|
||||||
public partial class XHttpProvider : XBaseClass, IXHttpProvider {
|
public partial class XHttpProvider : IXHttpProvider {
|
||||||
|
//
|
||||||
|
private readonly ILogger<XHttpProvider> logger;
|
||||||
private readonly XHttpServiceConfiguration configuration;
|
private readonly XHttpServiceConfiguration configuration;
|
||||||
|
|
||||||
public XHttpProvider (
|
public XHttpProvider (
|
||||||
ILoggerFactory loggerFactory,
|
ILogger<XHttpProvider> logger,
|
||||||
XHttpServiceConfiguration configuration
|
XHttpServiceConfiguration configuration
|
||||||
) : base (loggerFactory) {
|
)
|
||||||
|
{
|
||||||
|
this.logger = logger;
|
||||||
this.configuration = configuration;
|
this.configuration = configuration;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -32,70 +35,69 @@ namespace xHttpService.Providers {
|
|||||||
/// Get an Instance of Http Client
|
/// Get an Instance of Http Client
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public HttpClient GetHttpClient () {
|
public HttpClient GetHttpClient()
|
||||||
|
{
|
||||||
//
|
//
|
||||||
HttpClient httpClient = null;
|
HttpClient httpClient = null;
|
||||||
httpClient = new HttpClient ();
|
|
||||||
|
|
||||||
//
|
//
|
||||||
if (configuration.DisableSSLCheck) {
|
// httpClient = new HttpClient ();
|
||||||
|
var httpClientHandler = new HttpClientHandler()
|
||||||
|
{
|
||||||
|
ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) =>
|
||||||
|
{
|
||||||
//
|
//
|
||||||
var httpHandler = new HttpClientHandler ();
|
logger.LogInformation(
|
||||||
httpHandler.ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
|
$"XSSL Handler: {Environment.NewLine}, sender: {sender}, {Environment.NewLine} cert: {cert}, {Environment.NewLine} chain: {chain}, {Environment.NewLine} sslPolicyErrors: {sslPolicyErrors}"
|
||||||
|
);
|
||||||
|
|
||||||
//
|
//
|
||||||
httpClient = new HttpClient (httpHandler);
|
return true;
|
||||||
}
|
},
|
||||||
|
ClientCertificateOptions = ClientCertificateOption.Manual,
|
||||||
//
|
};
|
||||||
// Set Timeout ...
|
httpClient = new HttpClient(httpClientHandler);
|
||||||
httpClient.Timeout = TimeSpan
|
|
||||||
.FromSeconds (configuration.DefaultClientTimeout);
|
|
||||||
|
|
||||||
//
|
//
|
||||||
return httpClient;
|
return httpClient;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Get an Instance of RestClient
|
/// Retrieve Rest Client ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="baseUrl"></param>
|
/// <param name="baseUrl"></param>
|
||||||
/// <param name="poweredByValue"></param>
|
|
||||||
/// <param name="tokens"></param>
|
/// <param name="tokens"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public RestClient GetRestClient (
|
public RestClient GetRestClient(
|
||||||
string baseUrl = null,
|
string baseUrl = null,
|
||||||
string poweredByValue = null,
|
|
||||||
XTokenResponse tokens = null
|
XTokenResponse tokens = null
|
||||||
) {
|
)
|
||||||
|
{
|
||||||
//
|
//
|
||||||
var client = new RestClient (baseUrl);
|
var client = new RestClient(baseUrl);
|
||||||
|
|
||||||
//
|
|
||||||
// Add XPowered By to Default Headers ...
|
|
||||||
if (!poweredByValue.IsNullOrEmpty ()) {
|
|
||||||
client.AddDefaultHeader (XAuthorization.XPoweredBy, poweredByValue);
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
//
|
||||||
// Set Authenticator ...
|
// Set Authenticator ...
|
||||||
if (!tokens.IsNull () &&
|
if (!tokens.IsNull() &&
|
||||||
!tokens.AccessToken.IsNullOrEmpty ()) {
|
!tokens.AccessToken.IsNullOrEmpty())
|
||||||
client.Authenticator = new JwtAuthenticator (tokens.AccessToken);
|
{
|
||||||
|
client.Authenticator = new JwtAuthenticator(tokens.AccessToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
// Refresh Token ...
|
// Refresh Token ...
|
||||||
if (!tokens.IsNull () &&
|
if (!tokens.IsNull() &&
|
||||||
!tokens.RefreshToken.IsNullOrEmpty ()) {
|
!tokens.RefreshToken.IsNullOrEmpty())
|
||||||
client.AddDefaultHeader (XAuthorization.RefreshToken, tokens.RefreshToken);
|
{
|
||||||
|
client.AddDefaultHeader(XAuthorization.RefreshToken, tokens.RefreshToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
// ExpiresAt ...
|
// ExpiresAt ...
|
||||||
if (!tokens.IsNull () &&
|
if (!tokens.IsNull() &&
|
||||||
tokens.ExpiresAt > 0) {
|
tokens.ExpiresAt > 0)
|
||||||
client.AddDefaultHeader (XAuthorization.ExpiresAt, tokens.ExpiresAt.AsHttpParamString ());
|
{
|
||||||
|
client.AddDefaultHeader(XAuthorization.ExpiresAt, tokens.ExpiresAt.AsHttpParamString());
|
||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
@@ -104,79 +106,106 @@ namespace xHttpService.Providers {
|
|||||||
|
|
||||||
//
|
//
|
||||||
// SSL Validation Handler ...
|
// SSL Validation Handler ...
|
||||||
if (configuration.DisableSSLCheck) {
|
client.RemoteCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) =>
|
||||||
client.RemoteCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
|
{
|
||||||
}
|
//
|
||||||
|
logger.LogInformation(
|
||||||
|
$"XSSL Handler: {Environment.NewLine}, sender: {sender}, {Environment.NewLine} cert: {cert}, {Environment.NewLine} chain: {chain}, {Environment.NewLine} sslPolicyErrors: {sslPolicyErrors}"
|
||||||
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
//
|
//
|
||||||
return client;
|
return client;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Get an Instance of RestRequest
|
/// Prepare and Retrieve a Rest Request ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="endpoint"></param>
|
/// <param name="endpoint"></param>
|
||||||
|
/// <param name="poweredValue"></param>
|
||||||
/// <param name="params"></param>
|
/// <param name="params"></param>
|
||||||
/// <param name="headers"></param>
|
/// <param name="headers"></param>
|
||||||
/// <param name="queryStrings"></param>
|
/// <param name="queryStrings"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public RestRequest GetRestRequet (
|
public RestRequest GetRestRequet(
|
||||||
string endpoint,
|
string endpoint,
|
||||||
|
string poweredValue = null,
|
||||||
IDictionary<string, string> @params = null,
|
IDictionary<string, string> @params = null,
|
||||||
IDictionary<string, string> headers = null,
|
IDictionary<string, string> headers = null,
|
||||||
IDictionary<string, string> queryStrings = null
|
IDictionary<string, string> queryStrings = null
|
||||||
) {
|
)
|
||||||
|
{
|
||||||
//
|
//
|
||||||
var url = endpoint.ToString ();
|
var url = endpoint;
|
||||||
|
|
||||||
//
|
//
|
||||||
// Add Route Payloads ...
|
// Add Route Payloads ...
|
||||||
if (!@params.IsNull () && @params.Count > 0) {
|
if (!@params.IsNull() && @params.Count > 0)
|
||||||
|
{
|
||||||
//
|
//
|
||||||
var enumerator = @params.GetEnumerator ();
|
var enumerator = @params.GetEnumerator();
|
||||||
while (enumerator.MoveNext ()) {
|
while (enumerator.MoveNext())
|
||||||
|
{
|
||||||
//
|
//
|
||||||
var item = enumerator.Current;
|
var item = enumerator.Current;
|
||||||
|
|
||||||
//
|
//
|
||||||
url = url.Replace (item.Key, item.Value.ToUrlEncoded ());
|
url = url.Replace(item.Key, item.Value.ToUrlEncoded());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
// Add Query Strings ...
|
// Add Query Strings ...
|
||||||
if (!queryStrings.IsNull () && queryStrings.Count > 0) {
|
if (!queryStrings.IsNull() && queryStrings.Count > 0)
|
||||||
|
{
|
||||||
//
|
//
|
||||||
url = $"{url}?";
|
url = $"{url}?";
|
||||||
var enumerator = queryStrings.GetEnumerator ();
|
var enumerator = queryStrings.GetEnumerator();
|
||||||
while (enumerator.MoveNext ()) {
|
while (enumerator.MoveNext())
|
||||||
|
{
|
||||||
//
|
//
|
||||||
var item = enumerator.Current;
|
var item = enumerator.Current;
|
||||||
|
|
||||||
//
|
//
|
||||||
url += $"{item.Key}={item.Value.ToUrlEncoded ()}&";
|
url += $"{item.Key}={item.Value.ToUrlEncoded()}&";
|
||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
// remove lates & ...
|
// remove lates & ...
|
||||||
if (url.EndsWith ("&")) {
|
if (url.EndsWith("&"))
|
||||||
url = url.Substring (0, url.Length - 1);
|
{
|
||||||
|
url = url.Substring(0, url.Length - 1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
// Create request ...
|
// Create request ...
|
||||||
var request = new RestRequest (url, DataFormat.Json);
|
var request = new RestRequest(url, DataFormat.Json);
|
||||||
|
|
||||||
|
//
|
||||||
|
if (!poweredValue.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
//
|
||||||
|
request.AddHeader(
|
||||||
|
XAuthorization.XPoweredBy,
|
||||||
|
poweredValue
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
// Add Headers to request ...
|
// Add Headers to request ...
|
||||||
if (!headers.IsNull () && headers.Count > 0) {
|
if (!headers.IsNull() && headers.Count > 0)
|
||||||
|
{
|
||||||
//
|
//
|
||||||
var enumerator = headers.GetEnumerator ();
|
var enumerator = headers.GetEnumerator();
|
||||||
while (enumerator.MoveNext ()) {
|
while (enumerator.MoveNext())
|
||||||
|
{
|
||||||
//
|
//
|
||||||
var item = enumerator.Current;
|
var item = enumerator.Current;
|
||||||
request.AddHeader (item.Key, item.Value);
|
request.AddHeader(item.Key, item.Value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -190,82 +219,93 @@ namespace xHttpService.Providers {
|
|||||||
/// <param name="client"></param>
|
/// <param name="client"></param>
|
||||||
/// <param name="request"></param>
|
/// <param name="request"></param>
|
||||||
/// <param name="method"></param>
|
/// <param name="method"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
/// <typeparam name="T"></typeparam>
|
/// <typeparam name="T"></typeparam>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public async Task<T> RunRestRequest<T> (
|
public async Task<T> RunRestRequest<T>(
|
||||||
RestClient client,
|
RestClient client,
|
||||||
RestRequest request,
|
RestRequest request,
|
||||||
XHttpMethod method
|
XHttpMethod method,
|
||||||
) {
|
CancellationToken cancellationToken = default
|
||||||
|
)
|
||||||
|
{
|
||||||
//
|
//
|
||||||
var response = await Task.Run (() => {
|
var response = await Task.Run(async () =>
|
||||||
|
{
|
||||||
//
|
//
|
||||||
IRestResponse resp = null;
|
IRestResponse resp = null;
|
||||||
|
|
||||||
//
|
//
|
||||||
// Call Endpoint Service using Specified Method ...
|
// Call Endpoint Service using Specified Method ...
|
||||||
switch (method) {
|
switch (method)
|
||||||
|
{
|
||||||
//
|
//
|
||||||
// Get ...
|
// Get ...
|
||||||
case XHttpMethod.GET:
|
case XHttpMethod.GET:
|
||||||
resp = client.Get (request);
|
resp = client.Get(request);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
//
|
//
|
||||||
// Put ...
|
// Put ...
|
||||||
case XHttpMethod.PUT:
|
case XHttpMethod.PUT:
|
||||||
resp = client.Put (request);
|
resp = client.Put(request);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
//
|
//
|
||||||
// Post ...
|
// Post ...
|
||||||
case XHttpMethod.POST:
|
case XHttpMethod.POST:
|
||||||
resp = client.Post (request);
|
resp = client.Post(request);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
//
|
//
|
||||||
// Delete ...
|
// Delete ...
|
||||||
case XHttpMethod.DELETE:
|
case XHttpMethod.DELETE:
|
||||||
resp = client.Delete (request);
|
resp = client.Delete(request);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
if (!resp.IsSuccessful) {
|
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 ...
|
// UnAuthorized ...
|
||||||
if (resp.StatusCode == System.Net.HttpStatusCode.Unauthorized) {
|
if (resp.StatusCode == System.Net.HttpStatusCode.Unauthorized)
|
||||||
XException.NotAuthorized.Throw ();
|
{
|
||||||
|
XException.NotAuthorized.Throw();
|
||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
// NotFound ...
|
// NotFound ...
|
||||||
if (resp.StatusCode == System.Net.HttpStatusCode.NotFound) {
|
if (resp.StatusCode == System.Net.HttpStatusCode.NotFound)
|
||||||
XException.NotFound.Throw ();
|
{
|
||||||
|
XException.NotFound.Throw();
|
||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
// Timeout ...
|
XException.ActionFailed.Throw();
|
||||||
if (!resp.ErrorMessage.IsNullOrEmpty () &&
|
|
||||||
resp.ErrorMessage.Contains ("timed out")) {
|
|
||||||
XException.Timeout.Throw ();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
// ErrorMessage ...
|
var result = resp.Content.FromJSON<T>();
|
||||||
if (!resp.ErrorMessage.IsNullOrEmpty ()) {
|
|
||||||
throw new Exception (resp.ErrorMessage);
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
// Default Exception ...
|
|
||||||
XException.BadRequest.Throw ();
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
var result = resp.Content.FromJSON<T> ();
|
|
||||||
return result;
|
return result;
|
||||||
});
|
}, cancellationToken);
|
||||||
|
|
||||||
//
|
//
|
||||||
return response;
|
return response;
|
||||||
|
|||||||
@@ -37,6 +37,7 @@
|
|||||||
<PackageReference Include="RestSharp" Version="106.11.7" />
|
<PackageReference Include="RestSharp" Version="106.11.7" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Http" Version="2.2.0" />
|
<PackageReference Include="Microsoft.Extensions.Http" Version="2.2.0" />
|
||||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" />
|
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" />
|
||||||
|
<PackageReference Include="Microsoft.AspNetCore.Http.Features" Version="2.3.13" />
|
||||||
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.3.13" />
|
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.3.13" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user