Exemplo n.º 1
0
        private static HttpServerResponse GetUnauthorizedResponse(string realm)
        {
            var response = HttpServerResponse.Create(new Version(1, 1), HttpResponseStatus.Unauthorized);

            response.AddHeader("WWW-Authenticate", $"Basic realm=\"{realm}\"");
            return(response);
        }
        public async Task Invoke(HttpContext context, IEnumerable <IHttpServerEventCallback> callbacks)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (callbacks == null)
            {
                throw new ArgumentNullException(nameof(callbacks));
            }

            var stopwatch = Stopwatch.StartNew();

            callbacks.Invoke(() => HttpServerRequest.Create(context));

            try
            {
                await _next(context);
            }
            catch (HttpException e)
            {
                await WriteResponse(context, e.StatusCode, e.Message);
            }
            catch (Exception e)
            {
                await WriteResponse(context, HttpStatusCode.InternalServerError, "FAIL!");

                callbacks.Invoke(() => HttpServerException.Create(context, stopwatch.ElapsedMilliseconds, e));
            }

            callbacks.Invoke(() => HttpServerResponse.Create(context, stopwatch.ElapsedMilliseconds));
        }
Exemplo n.º 3
0
        public static HttpServerResponse CreateOkHttpServerResponse(byte[] content = null)
        {
            var response = HttpServerResponse.Create(new Version(1, 1), HttpResponseStatus.OK);

            response.Content = content;

            return(response);
        }
Exemplo n.º 4
0
        public void Create_EmptyResponse_HttpFirstLineOnly()
        {
            var response = HttpServerResponse.Create(HttpResponseStatus.OK);

            var responseMessage = response.ToString();
            var responseBytes   = response.ToBytes();

            AssertDefaultFirstLineOnly(responseMessage, responseBytes);
        }
Exemplo n.º 5
0
        private static HttpServerResponse GetDefaultResponse(IRestResponse response)
        {
            var serverResponse = HttpServerResponse.Create(response.StatusCode);

            serverResponse.Date = DateTime.Now;
            serverResponse.IsConnectionClosed = true;

            return(serverResponse);
        }
        public void serialise_server_response()
        {
            var httpServerResponse = HttpServerResponse.Create(_httpContext, 1358);

            httpServerResponse.Timestamp = new DateTimeOffset(2016, 11, 18, 19, 52, 6, TimeSpan.Zero).AddTicks(4425454);

            _testSubject.Invoke(httpServerResponse);

            _logger.Logs[0].ShouldBe("{\"eventType\":\"HttpServerResponse\",\"timestamp\":\"2016-11-18T19:52:06.4425454+00:00\",\"uri\":\"/ping?v=1\",\"method\":\"GET\",\"statusCode\":23,\"durationMs\":1358}");
        }
        private static HttpServerResponse GetFileNotFoundResponse(string localPath)
        {
            var notFoundResponse = HttpServerResponse.Create(new Version(1, 1), HttpResponseStatus.NotFound);

            notFoundResponse.Content        = Encoding.UTF8.GetBytes($"File at {localPath} not found.");
            notFoundResponse.ContentType    = "text/plain";
            notFoundResponse.ContentCharset = "utf-8";

            return(notFoundResponse);
        }
Exemplo n.º 8
0
        public void Create_HttpVersion2_HttpFirstLineOnly()
        {
            var response = HttpServerResponse.Create(new Version(2, 0), HttpResponseStatus.OK);

            var responseMessage = response.ToString();
            var responseBytes   = response.ToBytes();

            string expectedValue = "HTTP/2.0 200 OK\r\n\r\n";

            AssertResponse(expectedValue, responseMessage, responseBytes);
        }
Exemplo n.º 9
0
        public void Create_SetAndRemoveContent_FirstLineOnly()
        {
            var response = HttpServerResponse.Create(HttpResponseStatus.OK);

            response.Content = Encoding.UTF8.GetBytes("data");
            response.Content = null;

            var responseMessage = response.ToString();
            var responseBytes   = response.ToBytes();

            AssertDefaultFirstLineOnly(responseMessage, responseBytes);
        }
Exemplo n.º 10
0
        public void Create_SetAndremoveLocationRedirect_FirstLineOnly()
        {
            var response = HttpServerResponse.Create(HttpResponseStatus.OK);

            response.Location = new Uri("/api/1", UriKind.Relative);
            response.Location = null;

            var responseMessage = response.ToString();
            var responseBytes   = response.ToBytes();

            AssertDefaultFirstLineOnly(responseMessage, responseBytes);
        }
Exemplo n.º 11
0
        public void Create_AddAndRemoveCustomHeader_FirstLineOnly()
        {
            var response = HttpServerResponse.Create(HttpResponseStatus.OK);

            response.AddHeader("my-own-header", "23");
            response.RemoveHeader("my-own-header");

            var responseMessage = response.ToString();
            var responseBytes   = response.ToBytes();

            AssertDefaultFirstLineOnly(responseMessage, responseBytes);
        }
Exemplo n.º 12
0
        public void Create_SetAndRemoveDate_FirstLineOnly()
        {
            var response = HttpServerResponse.Create(HttpResponseStatus.OK);

            response.Date = DateTime.Parse("Tue, 15 Nov 1994 08:12:31");
            response.Date = null;

            var responseMessage = response.ToString();
            var responseBytes   = response.ToBytes();

            AssertDefaultFirstLineOnly(responseMessage, responseBytes);
        }
Exemplo n.º 13
0
        public void Create_SetAndUnsetConnectionClosed_FirstLineOnly()
        {
            var response = HttpServerResponse.Create(HttpResponseStatus.OK);

            response.IsConnectionClosed = true;
            response.IsConnectionClosed = false;

            var responseMessage = response.ToString();
            var responseBytes   = response.ToBytes();

            AssertDefaultFirstLineOnly(responseMessage, responseBytes);
        }
Exemplo n.º 14
0
        public void Create_SetAndRemoveContentType_FirstLineOnly()
        {
            var response = HttpServerResponse.Create(HttpResponseStatus.OK);

            response.ContentType = "application/json";
            response.ContentType = null;

            var responseMessage = response.ToString();
            var responseBytes   = response.ToBytes();

            AssertDefaultFirstLineOnly(responseMessage, responseBytes);
        }
Exemplo n.º 15
0
        public void Create_CustomHeader_AsHeader()
        {
            var response = HttpServerResponse.Create(HttpResponseStatus.OK);

            response.AddHeader("my-own-header", "23");

            var responseMessage = response.ToString();
            var responseBytes   = response.ToBytes();

            string expectedValue = "HTTP/1.1 200 OK\r\nmy-own-header: 23\r\n\r\n";

            AssertResponse(expectedValue, responseMessage, responseBytes);
        }
Exemplo n.º 16
0
        public void Create_Date_DateInCorrectFormat()
        {
            var response = HttpServerResponse.Create(HttpResponseStatus.OK);

            response.Date = DateTime.Parse("Tue, 15 Nov 1994 08:12:31");

            var responseMessage = response.ToString();
            var responseBytes   = response.ToBytes();

            string expectedValue = "HTTP/1.1 200 OK\r\nDate: Tue, 15 Nov 1994 08:12:31 GMT\r\n\r\n";

            AssertResponse(expectedValue, responseMessage, responseBytes);
        }
Exemplo n.º 17
0
        public void Create_ConnectionClosed_ConnectionClosedHeader()
        {
            var response = HttpServerResponse.Create(HttpResponseStatus.OK);

            response.IsConnectionClosed = true;

            var responseMessage = response.ToString();
            var responseBytes   = response.ToBytes();

            string expectedValue = "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n";

            AssertResponse(expectedValue, responseMessage, responseBytes);
        }
Exemplo n.º 18
0
        public void Create_ContentType_ContentTypeHeader()
        {
            var response = HttpServerResponse.Create(HttpResponseStatus.OK);

            response.ContentType = "application/json";

            var responseMessage = response.ToString();
            var responseBytes   = response.ToBytes();

            string expectedValue = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n";

            AssertResponse(expectedValue, responseMessage, responseBytes);
        }
Exemplo n.º 19
0
        public void Create_LocationRedirect_LocationHeaderOnly()
        {
            var response = HttpServerResponse.Create(HttpResponseStatus.OK);

            response.Location = new Uri("/api/1", UriKind.Relative);

            var responseMessage = response.ToString();
            var responseBytes   = response.ToBytes();

            string expectedValue = "HTTP/1.1 200 OK\r\nLocation: /api/1\r\n\r\n";

            AssertResponse(expectedValue, responseMessage, responseBytes);
        }
Exemplo n.º 20
0
        private static HttpServerResponse GetDefaultResponse(IRestResponse response)
        {
            var serverResponse = HttpServerResponse.Create(response.StatusCode);

            serverResponse.Date = DateTime.Now;
            serverResponse.IsConnectionClosed = true;
            foreach (var header in response.Headers)
            {
                serverResponse.AddHeader(header.Key, header.Value);
            }

            return(serverResponse);
        }
        private static HttpServerResponse GetMethodNotAllowedResponse(HttpMethod?method)
        {
            // https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
            // The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource.
            var methodNotAllowedResponse = HttpServerResponse.Create(new Version(1, 1), HttpResponseStatus.MethodNotAllowed);

            methodNotAllowedResponse.Content        = Encoding.UTF8.GetBytes($"Unsupported method {method}.");
            methodNotAllowedResponse.Allow          = new[] { HttpMethod.GET };
            methodNotAllowedResponse.ContentType    = "text/plain";
            methodNotAllowedResponse.ContentCharset = "utf-8";

            return(methodNotAllowedResponse);
        }
Exemplo n.º 22
0
        public void Create_UpdateContentCharset_UpdatedCharset()
        {
            var response = HttpServerResponse.Create(HttpResponseStatus.OK);

            response.ContentType    = "application/json";
            response.ContentCharset = "utf-8";
            response.ContentCharset = "unicode";

            var responseMessage = response.ToString();
            var responseBytes   = response.ToBytes();

            string expectedValue = "HTTP/1.1 200 OK\r\nContent-Type: application/json;charset=unicode\r\n\r\n";

            AssertResponse(expectedValue, responseMessage, responseBytes);
        }
        private async Task <HttpServerResponse> GetHttpResponse(IFile item)
        {
            // todo: do validation on file extension, probably want to have a whitelist
            using (var inputStream = await item.OpenStreamForReadAsync())
            {
                var memoryStream = new MemoryStream();
                // slightly inefficient since we're reading the whole file into memory... Should probably expose the http response stream directly somehow
                await inputStream.CopyToAsync(memoryStream);

                var response = HttpServerResponse.Create(new Version(1, 1), HttpResponseStatus.OK);
                response.Content     = memoryStream.ToArray(); // and make another copy of the file... for now this will do
                response.ContentType = _mimeTypeProvider.GetMimeType(item);

                return(response);
            }
        }
Exemplo n.º 24
0
        private async Task <HttpServerResponse> AddContentEncodingAsync(HttpServerResponse httpResponse, IEnumerable <string> acceptEncodings)
        {
            var contentEncoder = _contentEncoderFactory.GetEncoder(acceptEncodings);
            var encodedContent = await contentEncoder.Encode(httpResponse.Content);

            var newResponse = HttpServerResponse.Create(httpResponse.HttpVersion, httpResponse.ResponseStatus);

            foreach (var header in httpResponse.Headers)
            {
                newResponse.AddHeader(header);
            }
            newResponse.Content = encodedContent;
            newResponse.AddHeader(new ContentLengthHeader(encodedContent?.Length ?? 0));

            var contentEncodingHeader = contentEncoder.ContentEncodingHeader;

            AddHeaderIfNotNull(contentEncodingHeader, newResponse);

            return(newResponse);
        }
Exemplo n.º 25
0
        internal async Task <Tuple <HttpServerResponse, RouteRegistration> > HandleRequestExAsync(IHttpServerRequest request)
        {
            var routeRegistration = _routes.FirstOrDefault(x => x.Match(request));

            if (routeRegistration == null)
            {
                return(Tuple.Create <HttpServerResponse, RouteRegistration>(HttpServerResponse.Create(new Version(1, 1), HttpResponseStatus.BadRequest), null));
            }

            var httpResponse = ApplyMessageInspectorsBeforeHandleRequest(request);

            if (httpResponse == null)
            {
                httpResponse = await routeRegistration.HandleAsync(request);
            }

            httpResponse = await AddContentEncodingAsync(httpResponse, request.AcceptEncodings);

            httpResponse = ApplyMessageInspectorsAfterHandleRequest(request, httpResponse);

            return(Tuple.Create(httpResponse, routeRegistration));
        }
Exemplo n.º 26
0
        public BeforeHandleRequestResult BeforeHandleRequest(IHttpServerRequest request)
        {
            // could potentially pass this as state between the before handle request and after handle request
            // but before that would need to see if the performance increase is worth it
            string allowOrigin;

            if (request.Method != HttpMethod.OPTIONS || !TryGetAllowOrigin(request.Origin, out allowOrigin))
            {
                return(null);
            }

            var httpResponse = HttpServerResponse.Create(HttpResponseStatus.OK);

            httpResponse.AddHeader(new AccessControlAllowMethodsHeader(new[] { HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE, HttpMethod.OPTIONS, }));
            // max age possible by chrome https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/core/loader/CrossOriginPreflightResultCache.cpp&l=40&rcl=1399481969
            httpResponse.AddHeader(new AccessControlMaxAgeHeader(10 * 60));
            if (request.AccessControlRequestHeaders.Any())
            {
                httpResponse.AddHeader(new AccessControlAllowHeadersHeader(request.AccessControlRequestHeaders));
            }

            return(new BeforeHandleRequestResult(httpResponse));
        }