Advertisement
Guest User

Untitled

a guest
Mar 21st, 2019
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 8.01 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Http;
  6. using System.Net.Http.Headers;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using System.Web.Http;
  10. using System.Web.Mvc;
  11. using HazelTree.Framework.General.Helpers;
  12. using HazelTree.Framework.Logging.Infrastructure;
  13. //using HazelTree.Framework.WebApiClient.Config;
  14. using SyncManager.Web.Common.Extensions;
  15. using static HazelTree.Framework.General.Helpers.SafeExecuteHelper;
  16.  
  17. namespace SyncManager.Web.Controllers
  18. {
  19.     //[System.Web.Http.Authorize]
  20.     public class ProxyController : ApiController
  21.     {
  22.         private readonly IProxyClient _proxyClient;
  23.         private readonly ILoggerProvider _logger;
  24.         public ProxyController(IProxyClient proxyClient, ILoggerProvider logger)
  25.         {
  26.             if (proxyClient == null) throw new ArgumentNullException(nameof(proxyClient));
  27.             if (logger == null) throw new ArgumentNullException(nameof(logger));
  28.  
  29.             _proxyClient = new ProxyClient(new HttpRequestMessageExtensions.ProxySettings(), new HttpRequestClientFactory());
  30.             _logger = logger;
  31.         }
  32.      
  33.         [System.Web.Http.AcceptVerbs("POST", "GET", "HEAD", "OPTIONS")]
  34.         //[ValidateAntiForgeryToken]
  35.         public async Task<HttpResponseMessage> Proxy(string url)
  36.         {
  37.             if (string.IsNullOrWhiteSpace(url)) throw new ArgumentNullException(nameof(url));
  38.  
  39.             try
  40.             {                
  41.                 string absoluteUrl = Settings.GetValue<string>("location", "syncManager:WebApi", defaultValueEnabled: false) + "/api/v1/" + url + Request.RequestUri.Query;
  42.                 _logger.Debug($"Proxy: from {Request.RequestUri.AbsolutePath} to {absoluteUrl}");
  43.  
  44.                 Request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", User.GetToken());
  45.  
  46.                 var result =  await _proxyClient.SendAsync(new Uri(absoluteUrl), Request, CancellationToken.None);
  47.                 return result;
  48.             }
  49.             catch (Exception ex)
  50.             {
  51.                 SafeExecute(
  52.                     () => _logger.Error(GetFullErrorMessage(ex)),
  53.                     e => _logger.Fatal(GetFullErrorMessage(e))
  54.                 );
  55.                 throw;
  56.             }
  57.         }
  58.  
  59.         [System.Web.Http.HttpGet]
  60.         public async Task<HttpResponseMessage> Navigate(string url)
  61.         {
  62.             if (string.IsNullOrWhiteSpace(url)) throw new ArgumentNullException(nameof(url));
  63.  
  64.             try
  65.             {
  66.                 var tokenParam = Request.GetQueryNameValuePairs().FirstOrDefault(x => x.Key == "token");
  67.  
  68.                 if (tokenParam.Key == "token")
  69.                 {
  70.                     Request.Headers.Authorization= new AuthenticationHeaderValue("Bearer", tokenParam.Value);
  71.                     string absoluteUrl = Request.RequestUri.Scheme + "://" + Request.RequestUri.Host + ":" + Request.RequestUri.Port + "/" + url;
  72.                     _logger.Debug($"Proxy: from {Request.RequestUri.AbsolutePath} to {absoluteUrl}");
  73.                     return await _proxyClient.SendAsync(new Uri(absoluteUrl), Request, CancellationToken.None);
  74.                 }
  75.  
  76.                 return new HttpResponseMessage(HttpStatusCode.BadRequest);
  77.             }
  78.             catch (Exception ex)
  79.             {
  80.                 SafeExecute(
  81.                     () => _logger.Error(GetFullErrorMessage(ex)),
  82.                     e => _logger.Fatal(GetFullErrorMessage(e))
  83.                 );
  84.                 throw;
  85.             }
  86.         }
  87.     }
  88.  
  89.     public interface IHttpRequestClientFactory
  90.     {
  91.         HttpClient CreateClient();
  92.  
  93.         HttpClient CreateClient(TimeSpan timeOut);
  94.     }
  95.  
  96.     public class HttpRequestClientFactory : IHttpRequestClientFactory
  97.     {
  98.         private static HttpMessageHandler _httpMessageHandler;
  99.  
  100.         public HttpClient CreateClient()
  101.         {
  102.             HttpClient httpClient = _httpMessageHandler == null ? new HttpClient() : new HttpClient(HttpRequestClientFactory._httpMessageHandler);
  103.             httpClient.DefaultRequestHeaders.Add("Keep-Alive", "false");
  104.             return httpClient;
  105.         }
  106.  
  107.         public HttpClient CreateClient(TimeSpan timeOut)
  108.         {
  109.             HttpClient client = this.CreateClient();
  110.             client.Timeout = timeOut;
  111.             return client;
  112.         }
  113.  
  114.         public static void UseHttpMessageHandler(HttpMessageHandler httpMessageHandler)
  115.         {
  116.             _httpMessageHandler = httpMessageHandler;
  117.         }
  118.     }
  119.  
  120.     public interface IProxyClient
  121.     {
  122.         Task<HttpResponseMessage> SendAsync(
  123.             Uri targetUri,
  124.             HttpRequestMessage request,
  125.             CancellationToken cancellationToken);
  126.     }
  127.  
  128.     public class ProxyClient : IProxyClient
  129.     {
  130.         private static readonly HashSet<HttpMethod> WithNoContentMethods = new HashSet<HttpMethod>()
  131.         {
  132.             HttpMethod.Get,
  133.             HttpMethod.Head
  134.         };
  135.         private readonly IHttpRequestClientFactory _httpRequestClientFactory;
  136.         private readonly IProxySettings _proxySettings;
  137.  
  138.         public ProxyClient(
  139.             IProxySettings proxySettings,
  140.             IHttpRequestClientFactory httpRequestClientFactory)
  141.         {
  142.             this._proxySettings = proxySettings;
  143.             this._httpRequestClientFactory = httpRequestClientFactory;
  144.         }
  145.  
  146.         public async Task<HttpResponseMessage> SendAsync(
  147.             Uri targetUri,
  148.             HttpRequestMessage request,
  149.             CancellationToken cancellationToken)
  150.         {
  151.             var proxySettings = new HashSet<HttpMethod>()
  152.             {
  153.                 HttpMethod.Get,
  154.                 HttpMethod.Head
  155.             };
  156.             if (targetUri == (Uri)null)
  157.                 throw new ArgumentNullException(nameof(targetUri));
  158.             if (request == null)
  159.                 throw new ArgumentNullException(nameof(request));
  160.             if (proxySettings.Contains(request.Method))
  161.                 request.Content = (HttpContent)null;
  162.             HttpRequestMessage requestToSend = request.Clone(true);
  163.             requestToSend.Headers.Host = targetUri.Authority;
  164.             requestToSend.RequestUri = targetUri;
  165.             HttpResponseMessage result = await this._httpRequestClientFactory.CreateClient(this._proxySettings.HttpClientTimeoutSec > 0 ? TimeSpan.FromSeconds((double)this._proxySettings.HttpClientTimeoutSec) : TimeSpan.FromSeconds(30.0)).SendAsync(requestToSend, cancellationToken).ConfigureAwait(false);
  166.             return result;
  167.         }
  168.     }
  169.  
  170.      internal static class HttpRequestMessageExtensions
  171.   {
  172.     public static HttpRequestMessage Clone(
  173.       this HttpRequestMessage req,
  174.       bool cloneContent = false)
  175.     {
  176.       HttpRequestMessage httpRequestMessage = new HttpRequestMessage(req.Method, req.RequestUri)
  177.       {
  178.         Version = req.Version
  179.       };
  180.       if (req.Content != null)
  181.       {
  182.         httpRequestMessage.Content = (HttpContent) new ByteArrayContent(req.Content.ReadAsByteArrayAsync().RunSync<byte[]>());
  183.         foreach (KeyValuePair<string, IEnumerable<string>> header in (HttpHeaders) req.Content.Headers)
  184.           httpRequestMessage.Content.Headers.TryAddWithoutValidation(header.Key, header.Value);
  185.       }
  186.       foreach (KeyValuePair<string, object> property in (IEnumerable<KeyValuePair<string, object>>) req.Properties)
  187.         httpRequestMessage.Properties.Add(property);
  188.       foreach (KeyValuePair<string, IEnumerable<string>> header in (HttpHeaders) req.Headers)
  189.         httpRequestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value);
  190.       return httpRequestMessage;
  191.     }
  192.  
  193.     public class ProxySettings : IProxySettings
  194.     {
  195.         public int HttpClientTimeoutSec
  196.         {
  197.             get
  198.             {
  199.                 return Settings.GetValue<int>(nameof(HttpClientTimeoutSec), (string)null, true);
  200.             }
  201.         }
  202.     }
  203.     }
  204.  
  205.      public interface IProxySettings
  206.      {
  207.          int HttpClientTimeoutSec { get; }
  208.      }
  209. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement