Beispiel #1
0
        public void Add(List <AddHeader> addHeaders, DownstreamResponse response)
        {
            foreach (var add in addHeaders)
            {
                if (add.Value.StartsWith('{') && add.Value.EndsWith('}'))
                {
                    var value = _placeholders.Get(add.Value);

                    if (value.IsError)
                    {
                        _logger.LogWarning($"Unable to add header to response {add.Key}: {add.Value}");
                        continue;
                    }

                    response.Headers.Add(new Header(add.Key, new List <string> {
                        value.Data
                    }));
                }
                else
                {
                    response.Headers.Add(new Header(add.Key, new List <string> {
                        add.Value
                    }));
                }
            }
        }
Beispiel #2
0
        private void WhenICallTheMiddlewareMultipleTimes(int times, Ocelot.DownstreamRouteFinder.DownstreamRouteHolder downstreamRoute)
        {
            var httpContexts = new List <HttpContext>();

            for (int i = 0; i < times; i++)
            {
                var httpContext = new DefaultHttpContext();
                httpContext.Response.Body = new FakeStream();
                httpContext.Items.UpsertDownstreamRoute(downstreamRoute.Route.DownstreamRoute[0]);
                httpContext.Items.UpsertTemplatePlaceholderNameAndValues(downstreamRoute.TemplatePlaceholderNameAndValues);
                httpContext.Items.UpsertDownstreamRoute(downstreamRoute);
                var clientId = "ocelotclient1";
                var request  = new HttpRequestMessage(new HttpMethod("GET"), _url);
                httpContext.Items.UpsertDownstreamRequest(new DownstreamRequest(request));
                httpContext.Request.Headers.TryAdd("ClientId", clientId);
                httpContexts.Add(httpContext);
            }

            foreach (var httpContext in httpContexts)
            {
                _middleware.Invoke(httpContext).GetAwaiter().GetResult();
                var ds = httpContext.Items.DownstreamResponse();
                _downstreamResponse = ds;
            }
        }
Beispiel #3
0
        public async Task <DownstreamResponse> Aggregate(List <DownstreamResponse> responses)
        {
            var aggregatedResponseContentAsString = string.Empty;

            aggregatedResponseContentAsString += "{";

            var contentList = responses.Select(async e => await e.Content.ReadAsStringAsync());

            for (int i = 0; i < responses.Count; i++)
            {
                if (i != 0)
                {
                    aggregatedResponseContentAsString += ",";
                }

                aggregatedResponseContentAsString += $"\"DownStreamResponse_{(i + 1).ToString()}\" : {await contentList.ElementAtOrDefault(i)}";
            }

            //aggregatedResponseContentAsString += string.Join(",", contentList
            //        .Select(c => $" \"DownStreamResponse\" : {c.ConfigureAwait(false).GetAwaiter().GetResult()}"));

            aggregatedResponseContentAsString += "}";

            var aggregatedResponse = new DownstreamResponse(new StringContent(aggregatedResponseContentAsString, System.Text.Encoding.UTF8, "application/json")
                                                            , (responses.Where(s => s.StatusCode != HttpStatusCode.OK).Any() ? HttpStatusCode.InternalServerError : HttpStatusCode.OK)
                                                            , responses.FirstOrDefault().Headers, responses.FirstOrDefault().ReasonPhrase);

            return(aggregatedResponse);
        }
Beispiel #4
0
        public async Task SetResponseOnHttpContext(HttpContext context, DownstreamResponse response)
        {
            //_removeOutputHeaders.Remove(response.Headers);

            //foreach (var httpResponseHeader in response.Headers)
            //{
            //    AddHeaderIfDoesntExist(context, httpResponseHeader);
            //}

            foreach (var httpResponseHeader in response.Content.Headers)
            {
                AddHeaderIfDoesntExist(context, new Header(httpResponseHeader.Key, httpResponseHeader.Value));
            }

            var content = await response.Content.ReadAsStreamAsync();

            AddHeaderIfDoesntExist(context, new Header("Content-Length", new[] { content.Length.ToString() }));

            context.Response.OnStarting(state =>
            {
                var httpContext = (HttpContext)state;

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

                return(Task.CompletedTask);
            }, context);

            using (content)
            {
                if (response.StatusCode != HttpStatusCode.NotModified && context.Response.ContentLength != 0)
                {
                    await content.CopyToAsync(context.Response.Body);
                }
            }
        }
Beispiel #5
0
        public async Task SetResponseOnHttpContext(HttpContext context, DownstreamResponse response)
        {
            _removeOutputHeaders.Remove(response.Headers);

            foreach (var httpResponseHeader in response.Headers)
            {
                AddHeaderIfDoesntExist(context, httpResponseHeader);
            }

            foreach (var httpResponseHeader in response.Content.Headers)
            {
                AddHeaderIfDoesntExist(context, new Header(httpResponseHeader.Key, httpResponseHeader.Value));
            }

            var content = await response.Content.ReadAsStreamAsync();

            if (response.Content.Headers.ContentLength != null)
            {
                AddHeaderIfDoesntExist(context, new Header("Content-Length", new [] { response.Content.Headers.ContentLength.ToString() }));
            }

            context.Response.StatusCode = (int)response.StatusCode;

            context.Response.HttpContext.Features.Get <IHttpResponseFeature>().ReasonPhrase = response.ReasonPhrase;

            using (content)
            {
                if (response.StatusCode != HttpStatusCode.NotModified && context.Response.ContentLength != 0)
                {
                    await content.CopyToAsync(context.Response.Body);
                }
            }
        }
Beispiel #6
0
        public void should_replace_downstream_base_url_with_ocelot_base_url()
        {
            const string downstreamUrl = "http://downstream.com/";

            var request =
                new HttpRequestMessage(HttpMethod.Get, "http://test.com")
            {
                RequestUri = new System.Uri(downstreamUrl)
            };

            var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.Accepted,
                                                  new List <KeyValuePair <string, IEnumerable <string> > >()
            {
                new KeyValuePair <string, IEnumerable <string> >("Location", new List <string> {
                    downstreamUrl
                })
            }, "");

            var fAndRs = new List <HeaderFindAndReplace>
            {
                new HeaderFindAndReplace("Location", "{DownstreamBaseUrl}", "http://ocelot.com/", 0)
            };

            this.Given(x => GivenTheHttpResponse(response))
            .And(x => GivenTheRequestIs(request))
            .And(x => GivenTheFollowingHeaderReplacements(fAndRs))
            .When(x => WhenICallTheReplacer())
            .Then(x => ThenTheHeaderShouldBe("Location", "http://ocelot.com/"))
            .BDDfy();
        }
Beispiel #7
0
        private static void ProcessRpcError(HttpContext context, RpcException e)
        {
            var content = new ApiResponse
            {
                ResponseCode = _statusNames.GetValueOrDefault(e.StatusCode, _defaultErrorStatus)
            };

            try
            {
                content.Errors = JsonConvert.DeserializeObject <IEnumerable <ApiError> >(e.Status.Detail).ToList();
            }
            catch (Exception)
            {
                content.Errors = new[] { new ApiError(e.Status.Detail, e.InnerException?.Message) };
            }

            var statusCode = _statusCodes.GetValueOrDefault(e.StatusCode, _defaultErrorCode);

            context.Response.ContentType = MediaTypeNames.Application.Json;
            var response = new DownstreamResponse(new GrpcHttpContent(content),
                                                  statusCode,
                                                  new List <Header>
            {
                new Header(HeaderNames.ContentType, new [] { MediaTypeNames.Application.Json })
            },
                                                  statusCode.ToString());

            context.Items.UpsertDownstreamResponse(response);
        }
Beispiel #8
0
        /// <summary>
        /// Aggreaget microservices response objects
        /// </summary>
        /// <param name="responses"></param>
        /// <returns></returns>
        public Task <DownstreamResponse> Aggregate(List <DownstreamContext> responses)
        {
            try
            {
                Task <string> vehiclesContent;
                Task <string> customersContent;
                string        vehiclesKey = responses.FirstOrDefault(r => r.DownstreamReRoute.Key.ToLower().Contains("vehicle")).DownstreamReRoute.Key;
                string        customerKey = responses.FirstOrDefault(r => r.DownstreamReRoute.Key.ToLower().Contains("customer")).DownstreamReRoute.Key;
                vehiclesContent  = responses.FirstOrDefault(r => r.DownstreamReRoute.Key.Equals(vehiclesKey)).DownstreamResponse.Content.ReadAsStringAsync();
                customersContent = responses.FirstOrDefault(r => r.DownstreamReRoute.Key.Equals(customerKey)).DownstreamResponse.Content.ReadAsStringAsync();

                List <ComposerModel> model = CreateComposerModel(vehiclesContent, customersContent);

                var stringContent = new StringContent(JsonConvert.SerializeObject(model))
                {
                    Headers = { ContentType = new MediaTypeHeaderValue("application/json") }
                };

                DownstreamResponse response =
                    new DownstreamResponse(stringContent, HttpStatusCode.OK,
                                           new List <KeyValuePair <string, IEnumerable <string> > >(), "OK");
                return(Task.FromResult(response));
            }
            catch
            {
                DownstreamResponse response =
                    new DownstreamResponse(null, HttpStatusCode.BadRequest,
                                           new List <KeyValuePair <string, IEnumerable <string> > >(), "BadRequest");
                return(Task.FromResult(response));
            }
        }
        public async Task <DownstreamResponse> Aggregate(List <DownstreamContext> responses)
        {
            var responseStrings = responses.Select(response => {
                return(response.DownstreamResponse.Content.ReadAsStringAsync());
            }).ToList();
            var resp = new StringContent($"{{\"command\": {await responseStrings[0]}, \"price\": {await responseStrings[1]}}}");
            var dst  = new DownstreamResponse(resp, System.Net.HttpStatusCode.OK, new List <KeyValuePair <string, IEnumerable <string> > >(), "OK");

            return(dst);
        }
        public void should_have_content_length()
        {
            var httpContext = new DefaultHttpContext();
            var response    = new DownstreamResponse(new StringContent("test"), HttpStatusCode.OK,
                                                     new List <KeyValuePair <string, IEnumerable <string> > >());

            _responder.SetResponseOnHttpContext(httpContext, response).GetAwaiter().GetResult();
            var header = httpContext.Response.Headers["Content-Length"];

            header.First().ShouldBe("4");
        }
Beispiel #11
0
        public void should_add_reason_phrase()
        {
            var httpContext = new DefaultHttpContext();
            var response    = new DownstreamResponse(new StringContent(""), HttpStatusCode.OK,
                                                     new List <KeyValuePair <string, IEnumerable <string> > >
            {
                new KeyValuePair <string, IEnumerable <string> >("test", new List <string> {
                    "test"
                })
            }, "some reason");

            _responder.SetResponseOnHttpContext(httpContext, response).GetAwaiter().GetResult();
            httpContext.Response.HttpContext.Features.Get <IHttpResponseFeature>().ReasonPhrase.ShouldBe(response.ReasonPhrase);
        }
        public async Task Invoke(HttpContext context)
        {
            object result         = null;
            var    errMessage     = string.Empty;
            var    httpStatusCode = HttpStatusCode.OK;
            var    buildRequest   = grpcRequestBuilder.BuildRequest(context);

            if (buildRequest.IsError)
            {
                errMessage     = "bad request";
                httpStatusCode = HttpStatusCode.BadRequest;
                Logger.LogWarning(errMessage);
            }
            else
            {
                try
                {
                    var channel = grpcPool.GetChannel(new GrpcServiceEndpoint(context.Request.Host.Host, context.Request.Host.Port ?? 80));
                    var client  = new GrpcMethodDescriptorClient(channel);
                    result = await client.InvokeAsync(buildRequest.Data.GrpcMethod, buildRequest.Data.Headers, buildRequest.Data.RequestMessage);
                }
                catch (GrpcException ex)
                {
                    httpStatusCode = HttpStatusCode.InternalServerError;
                    errMessage     = $"rpc exception.";
                    Logger.LogError($"{ex.StatusCode}--{ex.Message}", ex);
                }
                catch (Exception ex)
                {
                    httpStatusCode = HttpStatusCode.ServiceUnavailable;
                    errMessage     = $"error in request grpc service.";
                    Logger.LogError($"{errMessage}--{context.Request.Path.Value}", ex);
                }
            }
            OkResponse <GrpcHttpContent> httpResponse;

            if (string.IsNullOrEmpty(errMessage))
            {
                httpResponse = new OkResponse <GrpcHttpContent>(new GrpcHttpContent(result));
            }
            else
            {
                httpResponse = new OkResponse <GrpcHttpContent>(new GrpcHttpContent(errMessage));
            }
            context.Response.ContentType = "application/json";
            var downstreamResponse = new DownstreamResponse(httpResponse.Data, httpStatusCode, httpResponse.Data.Headers,
                                                            "OcelotGrpcHttpMiddleware");
            //TODO: ???
            //context.Response.Write =;
        }
Beispiel #13
0
        public void should_ignore_content_if_null()
        {
            var httpContext = new DefaultHttpContext();
            var response    = new DownstreamResponse(null, HttpStatusCode.OK,
                                                     new List <KeyValuePair <string, IEnumerable <string> > >(), "some reason");

            Should.NotThrow(() =>
            {
                _responder
                .SetResponseOnHttpContext(httpContext, response)
                .GetAwaiter()
                .GetResult()
                ;
            });
        }
        public void should_cache_content_headers()
        {
            var content = new StringContent("{\"Test\": 1}")
            {
                Headers = { ContentType = new MediaTypeHeaderValue("application/json") }
            };

            var response = new DownstreamResponse(content, HttpStatusCode.OK, new List <KeyValuePair <string, IEnumerable <string> > >(), "fooreason");

            this.Given(x => x.GivenResponseIsNotCached(response))
            .And(x => x.GivenTheDownstreamRouteIs())
            .When(x => x.WhenICallTheMiddleware())
            .Then(x => x.ThenTheContentTypeHeaderIsCached())
            .BDDfy();
        }
        public void should_remove_transfer_encoding_header()
        {
            var httpContext = new DefaultHttpContext();
            var response    = new DownstreamResponse(new StringContent(""), HttpStatusCode.OK,
                                                     new List <KeyValuePair <string, IEnumerable <string> > >
            {
                new KeyValuePair <string, IEnumerable <string> >("Transfer-Encoding", new List <string> {
                    "woop"
                })
            });

            _responder.SetResponseOnHttpContext(httpContext, response).GetAwaiter().GetResult();
            var header = httpContext.Response.Headers["Transfer-Encoding"];

            header.ShouldBeEmpty();
        }
Beispiel #16
0
        public void should_add_header()
        {
            var httpContext = new DefaultHttpContext();
            var response    = new DownstreamResponse(new StringContent(""), HttpStatusCode.OK,
                                                     new List <KeyValuePair <string, IEnumerable <string> > >
            {
                new KeyValuePair <string, IEnumerable <string> >("test", new List <string> {
                    "test"
                })
            }, "some reason");

            _responder.SetResponseOnHttpContext(httpContext, response).GetAwaiter().GetResult();
            var header = httpContext.Response.Headers["test"];

            header.First().ShouldBe("test");
        }
Beispiel #17
0
        public async Task SetErrorResponseOnContext(HttpContext context, DownstreamResponse response)
        {
            var content = await response.Content.ReadAsStreamAsync();

            if (response.Content.Headers.ContentLength != null)
            {
                AddHeaderIfDoesntExist(context, new Header("Content-Length", new[] { response.Content.Headers.ContentLength.ToString() }));
            }

            using (content)
            {
                if (context.Response.ContentLength != 0)
                {
                    await content.CopyToAsync(context.Response.Body);
                }
            }
        }
Beispiel #18
0
        public void should_not_replace_headers()
        {
            var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.Accepted,
                                                  new List <KeyValuePair <string, IEnumerable <string> > >()
            {
                new KeyValuePair <string, IEnumerable <string> >("test", new List <string> {
                    "test"
                })
            }, "");

            var fAndRs = new List <HeaderFindAndReplace>();

            this.Given(x => GivenTheHttpResponse(response))
            .And(x => GivenTheFollowingHeaderReplacements(fAndRs))
            .When(x => WhenICallTheReplacer())
            .Then(x => ThenTheHeadersAreNotReplaced())
            .BDDfy();
        }
        public async Task <DownstreamResponse> SendRequestAsync(DownstreamRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            try
            {
                var response = await _httpClient.SendAsync(request);

                return(await DownstreamResponse.FromHttpResponseAsync(response, request));
            }
            catch (Exception ex)
            {
                return(DownstreamResponse.FromException(ex));
            }
        }
Beispiel #20
0
        private static void ProcessError(HttpContext context, Exception e)
        {
            var content = new GrpcHttpContent(new ApiResponse
            {
                ResponseCode = _defaultErrorStatus,
                Errors       = new[] { new ApiError(e.Message, e.InnerException?.Message) }
            });

            context.Response.ContentType = MediaTypeNames.Application.Json;
            var response = new DownstreamResponse(content,
                                                  _defaultErrorCode,
                                                  new List <Header>
            {
                new Header(HeaderNames.ContentType, new [] { MediaTypeNames.Application.Json })
            },
                                                  _defaultErrorCode.ToString());

            context.Items.UpsertDownstreamResponse(response);
        }
        private static async Task <CachedResponse> CreateCachedResponse(DownstreamResponse response)
        {
            if (response == null)
            {
                return(null);
            }

            var statusCode = response.StatusCode;
            var headers    = response.Headers.ToDictionary(v => v.Key, v => v.Values);
            var body       = response.Content != null
                ? await response.Content.ReadAsStringAsync()
                : null;

            var contentHeaders = response.Content?.Headers.ToDictionary(v => v.Key, v => v.Value);

            var cached = new CachedResponse(statusCode, headers, body, contentHeaders, response.ReasonPhrase);

            return(cached);
        }
Beispiel #22
0
        public async Task <DownstreamResponse> Aggregate(List <DownstreamResponse> responses)
        {
            Console.WriteLine("This should be written but isn't");
            //return new Task<DownstreamResponse>(() =>
            //{
            //    return responses[0];
            //});
            //return responses[0];
            try
            {
                List <Result> returnResult = new List <Result>();
                foreach (var response in responses)
                {
                    var contentString = response.Content.ReadAsStringAsync().Result;
                    var content       = JsonConvert.DeserializeObject <Result>(contentString);
                    returnResult.Add(content);
                }

                HttpResponseMessage aaa = new HttpResponseMessage();
                aaa.StatusCode = System.Net.HttpStatusCode.OK;
                using (var httpClient = new HttpClient())
                {
                    var content = new StringContent(JsonConvert.SerializeObject(returnResult), encoding: Encoding.UTF8);
                    HttpResponseMessage response;
                    var                uri            = new Uri("http://localhost:5557/api/CP");
                    ServicePoint       serverPoint    = ServicePointManager.FindServicePoint(uri);
                    HttpRequestMessage requestMessage = CreateRequestMessage(uri, HttpMethod.Post, content);

                    response = await httpClient.SendAsync(requestMessage);

                    aaa.Content = response.Content;
                }
                //DownstreamResponse(HttpContent content, HttpStatusCode statusCode, List<Header> headers, string reasonPhrase);
                DownstreamResponse resultResponse = new DownstreamResponse(aaa);

                return(resultResponse);
            }
            catch (Exception e)
            {
                throw new Exception();
            }
        }
        public Response Replace(DownstreamResponse response, List <HeaderFindAndReplace> fAndRs, DownstreamRequest request)
        {
            foreach (var f in fAndRs)
            {
                var dict = response.Headers.ToDictionary(x => x.Key);

                //if the response headers contain a matching find and replace
                if (dict.TryGetValue(f.Key, out var values))
                {
                    //check to see if it is a placeholder in the find...
                    var placeholderValue = _placeholders.Get(f.Find, request);

                    if (!placeholderValue.IsError)
                    {
                        //if it is we need to get the value of the placeholder
                        var replaced = values.Values.ToList()[f.Index].Replace(placeholderValue.Data, f.Replace.LastCharAsForwardSlash());

                        response.Headers.Remove(response.Headers.First(item => item.Key == f.Key));
                        response.Headers.Add(new Header(f.Key, new List <string> {
                            replaced
                        }));
                    }
                    else
                    {
                        var replaced = values.Values.ToList()[f.Index].Replace(f.Find, f.Replace);

                        response.Headers.Remove(response.Headers.First(item => item.Key == f.Key));
                        response.Headers.Add(new Header(f.Key, new List <string> {
                            replaced
                        }));
                    }
                }
            }

            return(new OkResponse());
        }
Beispiel #24
0
        internal async Task <CachedResponse> CreateCachedResponse(DownstreamResponse response)
        {
            if (response == null)
            {
                return(null);
            }

            var    statusCode = response.StatusCode;
            var    headers    = response.Headers.ToDictionary(v => v.Key, v => v.Values);
            string body       = null;

            if (response.Content != null)
            {
                var content = await response.Content.ReadAsByteArrayAsync();

                body = Convert.ToBase64String(content);
            }

            var contentHeaders = response?.Content?.Headers.ToDictionary(v => v.Key, v => v.Value);

            var cached = new CachedResponse(statusCode, headers, body, contentHeaders, response.ReasonPhrase);

            return(cached);
        }
 private void GivenTheHttpResponseMessageIs(DownstreamResponse response)
 {
     _httpContext.Items.UpsertDownstreamResponse(response);
 }
 private void GivenResponseIsNotCached(DownstreamResponse response)
 {
     _downstreamContext.DownstreamResponse = response;
 }
Beispiel #27
0
 private void GivenTheHttpResponse(DownstreamResponse response)
 {
     _response = response;
 }
 private void GivenTheHttpResponseMessageIs(DownstreamResponse response)
 {
     _downstreamContext.DownstreamResponse = response;
 }
Beispiel #29
0
 private void SetHttpResponseMessageThisRequest(DownstreamContext context,
                                                DownstreamResponse response)
 {
     context.DownstreamResponse = response;
 }
Beispiel #30
0
 private void GivenAResponseMessage()
 {
     _response = new DownstreamResponse(new HttpResponseMessage());
 }