Пример #1
0
        public void ExtractRequest_FromHttp()
        {
            var headers = new HeaderDictionary()
            {
                { "bob", "dave" }
            };

            var bodyContent = "this is a test";

            var body = new MemoryStream();
            var sw   = new StreamWriter(body);

            sw.Write(bodyContent);
            sw.Flush();

            body.Position = 0;

            var mockRequest = new Mock <HttpRequest>();

            mockRequest.Setup(x => x.Headers).Returns(headers);
            mockRequest.Setup(x => x.Method).Returns("GET");
            mockRequest.Setup(x => x.Body).Returns(body);
            mockRequest.Setup(x => x.Path).Returns("/testing123");
            mockRequest.Setup(x => x.Query["bob"]).Returns("dave");

            var extractedRequest = new ExtractedRequest(mockRequest.Object);

            extractedRequest.Body.Should().Be(bodyContent);
            extractedRequest.Method.Should().Be("GET");
            extractedRequest.Path.Should().Be("/testing123");
            extractedRequest.Headers.Should().BeEquivalentTo(headers);
        }
Пример #2
0
        public static RestRequest GenerateRequestMessage(ExtractedRequest request, string uri)
        {
            var fullUrl = uri + request.Path;

            var restRequest = new RestRequest(fullUrl)
            {
                Method = HttpUtils.GetHttpMethod(request.Method)
            };

            if (restRequest.Method == Method.POST || restRequest.Method == Method.PUT)
            {
                restRequest.AddParameter("application/json", request.Body, ParameterType.RequestBody);
            }

            if (!string.IsNullOrEmpty(request.Query))
            {
                string[] splitQuery = request.Query.Replace("?", "").Split('&');

                foreach (var query in splitQuery)
                {
                    var queryParam = query.Split('=');
                    restRequest.AddQueryParameter(queryParam[0], queryParam[1]);
                }
            }

            foreach (var header in request.Headers)
            {
                restRequest.AddHeader(header.Key, header.Value);
            }

            return(restRequest);
        }
Пример #3
0
        public void ExtractRequest_IndividualSections()
        {
            var headers = new HeaderDictionary()
            {
                { "bob", "dave" }
            };

            var extractedRequest = new ExtractedRequest("/testing123", JsonConvert.SerializeObject("{\"test\":\"banana\"}"), "?bob=dave", headers, "GET");

            extractedRequest.Body.Should().Be(JsonConvert.SerializeObject("{\"test\":\"banana\"}"));
            extractedRequest.Method.Should().Be("GET");
            extractedRequest.Path.Should().Be("/testing123");
            extractedRequest.Headers.Should().BeEquivalentTo(headers);
        }
        public void GenerateRequestMessage()
        {
            var headers = new HeaderDictionary()
            {
                { "fruit", "banana" },
                { "game", "cards" }
            };

            var extractedRequest = new ExtractedRequest("/endpoint", "bob", "?dave=rodney", headers, "GET");

            var request = HttpRequestMessageFactory.GenerateRequestMessage(extractedRequest, "http://example.test.com");

            request.Method.Should().Be(Method.GET);
            request.Resource.Should().Be("http://example.test.com/endpoint");
        }
        public void Router_UndefinedRoute()
        {
            // Assemble
            var messageClient = new Mock <IMessageClient>();
            var httpClient    = new Mock <IHttpClient>();
            var router        = new Router(messageClient.Object, httpClient.Object);
            var headers       = new HeaderDictionary
            {
                { "X-Correlation-Id", Guid.NewGuid().ToString() }
            };
            ExtractedRequest request = new ExtractedRequest("/bob", "", "", headers, "GET");

            Func <Task> act = async() => await router.RouteRequest(request);

            act.Should().Throw <NotFoundCustomException>("Route not found");
        }
Пример #6
0
        public async Task <ExtractedResponse> SendRequest(ExtractedRequest request, Route route)
        {
            var apiUrl = connectionStrings[route.Destination.ApiName] ?? throw new ArgumentNullException();

            var originalPath = request.Path;

            request.Path = ConvertEndpoint(originalPath, route);

            IRestRequest restRequest = HttpRequestMessageFactory.GenerateRequestMessage(request, apiUrl);

            var response = await restClient.ExecuteTaskAsync(restRequest);

            if (response.ErrorException != null)
            {
                throw new CustomException("Request timed out", $"Request to {originalPath} timed out", (int)System.Net.HttpStatusCode.RequestTimeout);
            }

            return(new ExtractedResponse(response));
        }
Пример #7
0
        public async Task <ExtractedResponse> RouteRequest(ExtractedRequest request)
        {
            // Organise the path to the final endpoint
            string basePath = '/' + request.Path.Split('/')[1];

            ExtractedResponse response = new ExtractedResponse();

            // Get the correct endpoint for the route requested
            Route route;

            try
            {
                route = Endpoints.First(r => r.Endpoint.Equals(basePath));
            }
            catch
            {
                throw new NotFoundCustomException("Route not found", $"Route matching {basePath} not found");
            }

            if (route.Destination.RequiresAuthentication)
            {
                // Auth stuff would go here, throwing exception for now
                throw new NotAuthorizedCustomException("Unauthorized", "You do not have permission to access this resource");
            }

            if (route.TransportType == TransportType.Http)
            {
                response = await httpClient.SendRequest(request, route);
            }
            else if (route.TransportType == TransportType.MessageQueue)
            {
                messageClient.PushMessageIntoQueue(request.GetJsonBytes(), route.Destination.MessageQueue);

                response.Body       = "{message: \"Message client does not support responses at the moment\"}";
                response.StatusCode = HttpStatusCode.OK;
            }

            return(response);
        }
Пример #8
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IMessageClient messageClient, IHttpClient httpClient)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            Router router = new Router(messageClient, httpClient)
            {
                // Configuration included to help with HTTP API calls
                Configuration = Configuration
            };


            // Ignore requests to specified endpoints
            var ignoredRoutes = new List <string>()
            {
                "favicon.ico"
            };

            app.UseErrorHandler();
            app.UseMiddleware <IgnoreRoute>(ignoredRoutes);
            app.UseMiddleware <AddHeaders>();

            app.Run(async(context) =>
            {
                var extractedRequest = new ExtractedRequest(context.Request);
                messageClient.PushAuditMessage(extractedRequest.GetJsonBytes());

                var content = await router.RouteRequest(extractedRequest);
                context.Response.StatusCode = (int)content.StatusCode;
                content.Headers             = context.Response.Headers;

                messageClient.PushAuditMessage(content.GetJsonBytes());
                await context.Response.WriteAsync(content.Body);
            });
        }
        public async void HttpClientWrapper_ReturnsResponse()
        {
            var expectedResponse = new RestResponse()
            {
                StatusCode = HttpStatusCode.OK,
                Content    = "bob"
            };

            var mockedRestClient = new Mock <IRestClient>();

            mockedRestClient.Setup(s => s.ExecuteTaskAsync(It.IsAny <IRestRequest>())).ReturnsAsync(expectedResponse);

            var routes = new Dictionary <string, string>()
            {
                { "bob", "https://localhost:12345" }
            };

            var request = new ExtractedRequest("/bob", "bob", "", new HeaderDictionary(), "GET");

            var route = new Route()
            {
                Endpoint    = "/bob",
                Destination = new Destination()
                {
                    ApiName = "bob",
                    Uri     = "/bob"
                }
            };

            var httpClient = new HttpClientWrapper(routes, mockedRestClient.Object);

            var response = await httpClient.SendRequest(request, route);

            response.Body.Should().Be(expectedResponse.Content);
            response.StatusCode.Should().Be(expectedResponse.StatusCode);
        }