174 lines
8.7 KiB
C#
Executable File
174 lines
8.7 KiB
C#
Executable File
using Microsoft.Extensions.Configuration;
|
|
using Opsoft.NetCore.O3App.Shared;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Diagnostics;
|
|
using System.Net;
|
|
using System.Net.Http;
|
|
using System.Net.Http.Headers;
|
|
using System.Runtime.CompilerServices;
|
|
using System.Text;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Opsoft.NetCore.O3App.Infrastructure
|
|
{
|
|
/// <summary>
|
|
/// Represents a HttpClient that with warm up function. This class is abstract.
|
|
/// </summary>
|
|
/// <typeparam name="TCategoryName">The type who's name is used for the logger category name.</typeparam>
|
|
public abstract class HttpClientWithWarmUp<TCategoryName> where TCategoryName : class
|
|
{
|
|
const int DefaultMillisecondsDelay = 3000;
|
|
|
|
protected ILogger Logger { get; }
|
|
protected IConfiguration Configuration { get; }
|
|
protected IHttpClientFactory HttpClientFactory { get; set; }
|
|
|
|
private readonly HttpClient httpClient;
|
|
|
|
public HttpClientWithWarmUp(
|
|
ILogger<TCategoryName> logger,
|
|
IConfiguration configuration,
|
|
IHttpClientFactory httpClientFactory)
|
|
{
|
|
Logger = Guard.ArgumentNotNull(logger, nameof(logger));
|
|
Configuration = Guard.ArgumentNotNull(configuration, nameof(configuration));
|
|
HttpClientFactory = Guard.ArgumentNotNull(httpClientFactory, nameof(httpClientFactory));
|
|
|
|
httpClient = InitHttpClient() ?? throw new WebException("HttpClient Uninitialized");
|
|
}
|
|
|
|
protected abstract Uri BaseUri { get; }
|
|
|
|
protected virtual HttpClient InitHttpClient()
|
|
{
|
|
var httpClient = HttpClientFactory.CreateClient();
|
|
httpClient.BaseAddress = BaseUri;
|
|
httpClient.DefaultRequestHeaders.Connection.Add("keep-alive");
|
|
httpClient.Timeout = TimeSpan.FromMilliseconds(DefaultMillisecondsDelay);
|
|
//http warm up
|
|
var headRequest = new HttpRequestMessage(HttpMethod.Head, string.Empty);
|
|
var task = httpClient.SendAsync(headRequest);
|
|
Task.WaitAny(task);
|
|
var responesMessage = task.Result;
|
|
if (!responesMessage.IsSuccessStatusCode)
|
|
{
|
|
Logger.Warn(new { httpClient.BaseAddress.AbsoluteUri, responesMessage.StatusCode }, "WarmUp");
|
|
}
|
|
|
|
return httpClient;
|
|
}
|
|
|
|
protected virtual string GetBaseUrl(string url)
|
|
{
|
|
return $"{(url ?? string.Empty).Trim().TrimEnd(Constants.CharText.Slash).Trim()}{Constants.CharText.Slash}";
|
|
}
|
|
|
|
public async Task<string> GetAsync(string url, Encoding encoding = null, string filter1 = "", string filter2 = "", string callerName = "", int millisecondsDelay = DefaultMillisecondsDelay)
|
|
{
|
|
Dictionary<string, dynamic> extraInfo = new Dictionary<string, dynamic>();
|
|
extraInfo.Add("url", $"{httpClient.BaseAddress.AbsoluteUri}{url}");
|
|
extraInfo.Add("method", "get");
|
|
Stopwatch stopwatch = Stopwatch.StartNew();
|
|
string responseText = string.Empty;
|
|
|
|
try
|
|
{
|
|
if (url.StartsWith(Constants.Protocols.HTTPS, StringComparison.CurrentCultureIgnoreCase))
|
|
{
|
|
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
|
|
}
|
|
var cts = new CancellationTokenSource((millisecondsDelay <= 0 ? DefaultMillisecondsDelay : millisecondsDelay));
|
|
var response = await httpClient.GetAsync(url, cts.Token);
|
|
var resultBytes = response.IsSuccessStatusCode ? await response.Content.ReadAsByteArrayAsync() : Array.Empty<byte>();
|
|
|
|
responseText = (encoding ?? Encoding.UTF8).GetString(resultBytes);
|
|
stopwatch.Stop();
|
|
extraInfo.Add("Elapsed", stopwatch.ElapsedMilliseconds.ToString());
|
|
extraInfo.Add("responseText", responseText);
|
|
Logger.Debug(extraInfo, filter1, filter2, callerName);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
stopwatch.Stop();
|
|
extraInfo.Add("Elapsed", stopwatch.ElapsedMilliseconds.ToString());
|
|
extraInfo.Add("ex", ex);
|
|
Logger.Error(ex, extraInfo, filter1, filter2, callerName);
|
|
|
|
throw;
|
|
}
|
|
|
|
return responseText;
|
|
}
|
|
public async Task<T> GetAsync<T>(string url, Encoding encoding = null, string filter1 = "", string filter2 = "", int millisecondsDelay = DefaultMillisecondsDelay, [CallerMemberName]string callerName = "")
|
|
{
|
|
var response = await GetAsync(url, encoding, filter1, filter2, callerName, millisecondsDelay);
|
|
return response.IsNullOrWhiteSpace() ? default(T) : response.FromJson<T>();
|
|
}
|
|
public async Task<string> PostAsync(string url, string postData, IDictionary<string, string> headers = null, Encoding encoding = null, string filter1 = "", string filter2 = "", string callerName = "", int millisecondsDelay = DefaultMillisecondsDelay)
|
|
{
|
|
Dictionary<string, dynamic> extraInfo = new Dictionary<string, dynamic>();
|
|
extraInfo.Add("url", $"{httpClient.BaseAddress.AbsoluteUri}{url}");
|
|
extraInfo.Add("method", "post");
|
|
extraInfo.Add("requestText", postData);
|
|
Stopwatch stopwatch = Stopwatch.StartNew();
|
|
string responseText = string.Empty;
|
|
try
|
|
{
|
|
if (url.StartsWith(Constants.Protocols.HTTPS, StringComparison.CurrentCultureIgnoreCase))
|
|
{
|
|
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
|
|
}
|
|
var httpContent = new StringContent(postData);
|
|
httpContent.Headers.ContentType = new MediaTypeHeaderValue(Constants.ContentTypes.Json);
|
|
if (headers?.Count > 0)
|
|
{
|
|
foreach (var item in headers)
|
|
{
|
|
httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
|
|
}
|
|
}
|
|
|
|
var cts = new CancellationTokenSource((millisecondsDelay <= 0 ? DefaultMillisecondsDelay : millisecondsDelay));
|
|
var response = await httpClient.PostAsync(url, httpContent, cts.Token);
|
|
var resultBytes = response.IsSuccessStatusCode ? await response.Content.ReadAsByteArrayAsync() : Array.Empty<byte>();
|
|
|
|
responseText = (encoding ?? Encoding.UTF8).GetString(resultBytes);
|
|
stopwatch.Stop();
|
|
extraInfo.Add("Elapsed", stopwatch.ElapsedMilliseconds.ToString());
|
|
extraInfo.Add("responseText", responseText);
|
|
Logger.Debug(extraInfo, filter1, filter2, callerName);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
stopwatch.Stop();
|
|
extraInfo.Add("Elapsed", stopwatch.ElapsedMilliseconds.ToString());
|
|
extraInfo.Add("ex", ex);
|
|
Logger.Error(ex, extraInfo, filter1, filter2, callerName);
|
|
|
|
throw;
|
|
}
|
|
|
|
return responseText;
|
|
}
|
|
public async Task<T> PostAsync<T>(string url, string postData, IDictionary<string, string> headers = null, Encoding encoding = null, string filter1 = "", string filter2 = "", int millisecondsDelay = DefaultMillisecondsDelay, [CallerMemberName]string callerName = "")
|
|
{
|
|
var response = await PostAsync(url, postData, headers, encoding, filter1, filter2, callerName, millisecondsDelay);
|
|
return response.IsNullOrWhiteSpace() ? default(T) : response.FromJson<T>();
|
|
}
|
|
public async Task<TOut> PostAsync<TIn, TOut>(string url, TIn postData, IDictionary<string, string> headers = null, Encoding encoding = null, string filter1 = "", string filter2 = "", int millisecondsDelay = DefaultMillisecondsDelay, [CallerMemberName]string callerName = "")
|
|
where TOut : class, new()
|
|
{
|
|
var response = await PostAsync(url, postData.ToJson(), headers, encoding, filter1, filter2, callerName, millisecondsDelay);
|
|
return response.IsNullOrWhiteSpace() ? default(TOut) : response.FromJson<TOut>();
|
|
}
|
|
public async Task<T> PostWithXmlResponseAsync<T>(string url, string xmlString, IDictionary<string, string> headers = null, Encoding encoding = null, string filter1 = "", string filter2 = "", int millisecondsDelay = DefaultMillisecondsDelay, [CallerMemberName]string callerName = "")
|
|
where T : class, new()
|
|
{
|
|
var response = await PostAsync(url, xmlString, headers, encoding, filter1, filter2, callerName, millisecondsDelay);
|
|
return response.IsNullOrWhiteSpace() ? default(T) : response.FromXml<T>();
|
|
}
|
|
}
|
|
}
|