Esempio n. 1
0
        /// <summary>
        /// Sends provided message.
        /// </summary>
        /// <typeparam name="TResult">Assumed type of response.</typeparam>
        /// <param name="message">Request message instance.</param>
        /// <returns>Responce object.</returns>
        private async Task <TResult> SendAsync <TResult>(HttpRequestMessage message)
            where TResult : class, new()
        {
            using var response = await _httpClient.SendAsync(message, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);

            return(await ProcessResponseAsync <TResult>(response).ConfigureAwait(false));
        }
Esempio n. 2
0
        public async Task <ResponseContentModel> ReturnContent(HttpRequestMessage request,
                                                               Type expectedType,
                                                               Type expectedErrorType = null)
        {
            var successContentService = _contentServiceFactory.GetService(expectedType);
            var failureContentService = _contentServiceFactory.GetService(expectedErrorType);

            var startTime = _dateTime.Now;

            using (var response = await _client.SendAsync(request))
            {
                var completeTime = _dateTime.Now;

                object content = null;
                if (response.IsSuccessStatusCode && successContentService != null)
                {
                    content = await successContentService.ReadContent(response);
                }

                if (!response.IsSuccessStatusCode && failureContentService != null)
                {
                    content = await failureContentService.ReadContent(response);
                }

                return(new ResponseContentModel(completeTime - startTime,
                                                response.StatusCode,
                                                startTime,
                                                content));
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Perform the WebDAV call and fire the callback when finished.
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="method"></param>
        /// <param name="headers"></param>
        /// <param name="content"></param>
        private async Task <HttpResponseMessage> HttpRequest(Uri uri, HttpMethod method, IDictionary <string, string> headers = null, byte[] content = null)
        {
            using (var request = new HttpRequestMessage(method, uri))
            {
                request.Headers.Connection.Add("Keep-Alive");
                if (!string.IsNullOrWhiteSpace(UserAgent))
                {
                    request.Headers.UserAgent.Add(new ProductInfoHeaderValue(UserAgent, UserAgentVersion));
                }
                else
                {
                    request.Headers.UserAgent.Add(new ProductInfoHeaderValue("WebDAVClient", m_assemblyVersion));
                }

                if (headers != null)
                {
                    foreach (string key in headers.Keys)
                    {
                        request.Headers.Add(key, headers[key]);
                    }
                }

                // Need to send along content?
                if (content != null)
                {
                    request.Content = new ByteArrayContent(content);
                    request.Content.Headers.ContentType = new MediaTypeHeaderValue("text/xml");
                }

                return(await m_httpClientWrapper.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false));
            }
        }
Esempio n. 4
0
        public async Task <HttpResponseMessage> SendAsync(HttpClient client, HttpRequestMessage request, CancellationToken cancellationToken)
        {
            foreach (var filter in filters)
            {
                await filter.Filter(request, cancellationToken);
            }

            var rsp = await clientWrapper.SendAsync(client, request, cancellationToken);

            try
            {
                foreach (var filter in filters)
                {
                    await filter.Filter(rsp, cancellationToken);
                }
            }
            catch
            {
                rsp.Dispose();

                throw;
            }

            return(rsp);
        }
Esempio n. 5
0
        public async Task <HttpResponseMessage> GetAsync(Url url)
        {
            url = ValidateUrl(url);

            var request = new HttpRequestMessage
            {
                Method     = HttpMethod.Get,
                RequestUri = url.ToUri()
            };

            var response = await _httpClient
                           .SendAsync(request)
                           .ConfigureAwait(false);

            return(response);
        }
        private async Task <HttpResponseMessage> SendRequestAndCheckStatus(IHttpClientWrapper clientWrapper, HttpRequestMessage requestMessage)
        {
            var response = await clientWrapper.SendAsync(requestMessage);

            await CheckResponseStatus(response);

            return(response);
        }
Esempio n. 7
0
            public async Task <TResult> SendAsync <TResult>(HttpRequest <TResult> httpRequest, CancellationToken cancellationToken)
            {
                return((TResult)(await this.func(
                                     async(innerHttpRequest, innerCt) =>
                {
                    var result = await httpClientWrapper.SendAsync(ConvertHttpRequest <object, TResult>(innerHttpRequest), innerCt).ConfigureAwait(false);

                    return result;
                },
                                     ConvertHttpRequest <TResult, object>(httpRequest),
                                     typeof(TResult),
                                     cancellationToken).ConfigureAwait(false)));
            }
        private async Task <string> RequestApiAsync(string apiKey, ApiFunction function,
                                                    IDictionary <string, string>?query)
        {
            var request = ComposeHttpRequest(_apiKey, function, query);

            var response = await _httpClient.SendAsync(request)
                           .ConfigureAwait(false);

            var jsonString = await response.Content.ReadAsStringAsync()
                             .ConfigureAwait(false);

            return(jsonString);
        }
Esempio n. 9
0
        private async Task <HttpResponseMessage> SendRequestAsync(HttpMethod method, string url, object data = null, string customToken = null)
        {
            using (var requestMessage = new HttpRequestMessage(method, url))
            {
                SetAutorizationHeader(customToken, requestMessage);

                await SetContent(data, requestMessage);

                var response = await client.SendAsync(requestMessage).ConfigureAwait(false);

                return(response);
            }
        }
Esempio n. 10
0
        private async Task <HttpResponseMessage> SendAsync(
            HttpMethod method,
            string path,
            IDictionary <string, string> query,
            HttpContent content,
            IDictionary <string, string> headers,
            CancellationToken cancellationToken)
        {
            string dateTimeReference = _dateTime.Now.ToString("R");

            headers.Add("x-ms-date", dateTimeReference);
            headers.Add("x-ms-version", ApiVersion);

            string canonicalisedHeaders   = CreateCanonicalisedHeaders(headers);
            string canonicalisedResources = CreateCanonicalisedResources(query);
            string queryString            = CreateQueryString(query);
            var    uri = new Uri($"{_baseUri}/{path}?{queryString}");

            string signature = GenerateSignature(method.Method,
                                                 contentLength: content.Headers.ContentLength > 0 ? content.Headers.ContentLength.ToString() : "",
                                                 range: headers.ContainsKey("range") ? headers["range"] : "",
                                                 canonicalisedHeaders: canonicalisedHeaders,
                                                 canonicalisedResource: $"/{_storageAccountName}{uri.AbsolutePath}\n{canonicalisedResources}"
                                                 );

            var request = new HttpRequestMessage
            {
                Method     = method,
                Content    = content,
                RequestUri = uri,
                Headers    = { Authorization = await _authorisation.AuthoriseAsync(_storageAccountName, signature) }
            };

            headers.ToList().ForEach(x => request.Headers.Add(x.Key, x.Value));

            HttpResponseMessage result = await _httpClient.SendAsync(request, cancellationToken);

            try
            {
                result.EnsureSuccessStatusCode();
            }
            catch (Exception e)
            {
                throw new DataLakeGen2Exception("Exception occurred during call to Data Lake Gen 2 Rest API.", e)
                      {
                          StatusCode = result.StatusCode
                      };
            }

            return(result);
        }
Esempio n. 11
0
        private async Task <HttpResponseMessage> SendRequestAsync(HttpMethod method, string url, object data = null, string customToken = null, string username = null, string password = null, FormUrlEncodedContent encodedContent = null)
        {
            using (var requestMessage = new HttpRequestMessage(method, url))
            {
                SetAutorizationHeader(requestMessage, customToken, username, password);

                await SetContent(data, requestMessage, encodedContent);

                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                var response = await client.SendAsync(requestMessage).ConfigureAwait(false);

                return(response);
            }
        }
Esempio n. 12
0
        public async Task ProxyTheRequest(HttpContext context, HttpRequestMessage proxyRequest, IWMSRule proxyRule)
        {
            try
            {
                using (var responseMessage = await _httpClientWrapper.SendAsync(proxyRequest, context.RequestAborted))
                {
                    if (proxyRule.PreProcessResponse)
                    {
                        await _wmsMessageProcessor.PreProcess(context, responseMessage);
                    }

                    await proxyRule.ResponseModifier(responseMessage, context);
                }
            }
            catch (Exception ex) {
            }
        }
Esempio n. 13
0
        private async Task <HttpResponseMessage> SendRequestAsync(HttpMethod method, string url, object data = null, Dictionary <string, string> headers = null)
        {
            using (var requestMessage = new HttpRequestMessage(method, url))
            {
                await SetContent(data, requestMessage);

                if (headers != null)
                {
                    foreach (var i in headers)
                    {
                        requestMessage.Headers.Add(i.Key, i.Value);
                    }
                }

                return(await client.SendAsync(requestMessage).ConfigureAwait(false));
            }
        }
        /// <summary>
        /// Proxy the incoming request to the remote host. This method will mutate the HttpContext response property by
        /// copying the content body, headers, and status code from the proxied HTTP request.
        /// </summary>
        /// <param name="httpContext">The HttpContext of the incoming request.</param>
        /// <param name="template">The template (relative route).</param>
        /// <returns>An asynchronous Task instance.</returns>
        public async Task Proxy(HttpContext httpContext, string template)
        {
            var targetUri            = new Uri($"{_baseUrl}{template}");
            var targetRequestMessage = CreateTargetMessage(httpContext, targetUri);

            var proxiedResponse = await _httpClient.SendAsync(
                targetRequestMessage
                , HttpCompletionOption.ResponseHeadersRead
                , httpContext.RequestAborted
                );

            httpContext.Response.StatusCode = (int)proxiedResponse.StatusCode;

            CopyFromTargetResponseHeaders(httpContext, proxiedResponse);

            await proxiedResponse
            .Content
            .CopyToAsync(httpContext.Response.Body);
        }
Esempio n. 15
0
        public async Task <QuotationResponseDTO> GetQuotation(string currency)
        {
            var client = _clientFactory.CreateClient("cambio.today");
            var url    =
                $"quotes/{CurrencyMapper.Map(currency)}/ARS/json?quantity=1&key={_cambioTodaySettings.Key}";
            var request  = new HttpRequestMessage(HttpMethod.Get, url);
            var response = await _clientWrapper.SendAsync(client, request);

            if (!response.IsSuccessStatusCode)
            {
                throw new CambioTodayAPIException(CAMBIOTODAYAPI_ERROR_MESSAGE);
            }
            var contentResponse = await response.Content.ReadAsStringAsync();

            var cambioTodayResponse = JsonConvert.DeserializeObject <QuotesModelCTResponse>(contentResponse);
            var quotationResponse   = _mapper.Map <QuotationResponseDTO>(cambioTodayResponse.Result);

            return(quotationResponse);
        }
        public async Task <string> Get()
        {
            const string url = "https://www.google.com";

            // normally this would be defined more centrally but including here for a quick example
            var retryPolicy = Policy
                              .Handle <HttpRequestException>()
                              .WaitAndRetryAsync(2, retryCount => TimeSpan.FromSeconds(2),
                                                 (exception, timeSpan, retryCount, context) =>
            {
                _logger.LogWarning(
                    $"Call to {url} failed - Retry {retryCount} : TimeSpan {timeSpan} : Ex {exception.Message}");
            });

            var response = await retryPolicy.ExecuteAsync(() =>
            {
                var request = new HttpRequestMessage(HttpMethod.Get, url);
                return(_httpClientWrapper.SendAsync(request));
            });

            return(response.IsSuccessStatusCode ? "ok" : "not ok");
        }
Esempio n. 17
0
        public async Task <int[]> Search(SearchRequest searchRequest)
        {
            var array          = searchRequest.Keywords.Split(',');
            var searchKeywords = array.Select(k => k.Trim());
            var results        = new List <int>();

            foreach (var keyword in searchKeywords)
            {
                if (keyword == string.Empty)
                {
                    results.Add(0);
                }
                else
                {
                    var requestUrl   = $"{_searchOptions.SearchUrl}/search?q={HttpUtility.UrlEncode(keyword)}&num={_searchOptions.ResultSize}";
                    var request      = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                    var searchResult = await _httpClientWrapper.SendAsync(request);

                    results.Add(_matchService.Count(searchResult, searchRequest.Url));
                }
            }

            return(results.ToArray());
        }
Esempio n. 18
0
        public async Task <List <ServiceMetricsResponse> > GetResposesAsync(List <HttpRequestMessage> httpRequestMessages)
        {
            var responseTasks = new List <Task <HttpResponseMessage> >();

            foreach (var httpRequestMessage in httpRequestMessages)
            {
                responseTasks.Add(httpClientWrapper.SendAsync(httpRequestMessage));
            }

            var serviceMetricsResponses = new List <ServiceMetricsResponse>();

            foreach (var responseTask in responseTasks)
            {
                HttpResponseMessage response;
                try
                {
                    response = responseTask.Result;
                }
                catch (AggregateException)
                {
                    continue;
                }

                if (!response.IsSuccessStatusCode)
                {
                    continue;
                }

                var serviceMetricsResponse = await response.Content.ReadAsStringAsync();

                var serviceMetricsModel = JsonConvert.DeserializeObject <ServiceMetricsResponse>(serviceMetricsResponse);
                serviceMetricsResponses.Add(serviceMetricsModel);
            }

            return(serviceMetricsResponses);
        }
Esempio n. 19
0
        private async Task <HttpResponseMessage> GetSubscriptionsAsync(HttpRequestMessage requestMessage)
        {
            var sendRequest = new HttpRequestMessage(HttpMethod.Get, string.Format(Utils.AllSubscriptionsTemplate, HyakUtils.CSMUrl, Utils.CSMApiVersion));

            return(await _clientWrapper.SendAsync(requestMessage, sendRequest));
        }