Example #1
0
            public Task ProcessRequestAsync(HttpContextPipelineHandlerContext context)
            {
                if (context.HttpContext.Request.Uri.Equals("/404test"))
                {
                    context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
                    return(Task.FromResult(0));
                }

                if (context.HttpContext.Request.Method.Equals(HttpMethod.Post) && context.HttpContext.Request.Uri.Equals("/toUpper"))
                {
                    var s = new StreamReader(context.HttpContext.Request.Body).ReadToEnd();
                    context.HttpContext.Response.Body       = new MemoryStream(Encoding.UTF8.GetBytes(s.ToUpperInvariant()));
                    context.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK; // OK is also default
                    return(Task.FromResult(0));
                }

                var filename = "C:" + context.HttpContext.Request.Uri.Replace("/", "\\");

                if (File.Exists(filename))
                {
                    // Return a file from the filesystem.
                    context.HttpContext.Response.Body = File.OpenRead(filename);
                }
                else
                {
                    // Return a static text.
                    context.HttpContext.Response.Body = new MemoryStream(Encoding.UTF8.GetBytes("Hello World"));
                }

                return(Task.FromResult(0));
            }
        public async Task ProcessResponseAsync(HttpContextPipelineHandlerContext context)
        {
            if (context.HttpContext.Response.Body == null || context.HttpContext.Response.Body.Length == 0)
            {
                return;
            }

            if (!ClientSupportsGzipCompression(context.HttpContext.Request.Headers))
            {
                return;
            }

            context.HttpContext.Response.Headers[HttpHeader.ContentEncoding] = "gzip";

            var compressedBody = new MemoryStream();

            using (var zipStream = new GZipStream(compressedBody, CompressionLevel.Fastest, true))
            {
                context.HttpContext.Response.Body.Position = 0;
                await context.HttpContext.Response.Body.CopyToAsync(zipStream);
            }

            compressedBody.Position           = 0;
            context.HttpContext.Response.Body = compressedBody;
        }
Example #3
0
        private void ValidateRequestFormat([NotNull] HttpContextPipelineHandlerContext context, [NotNull] out JsonRpcRequestBase payload)
        {
            var c = RpcSessionContext.Wrap(context);

            foreach (var validator in _validators)
            {
                validator.Validate(c);
            }

            var body = context.HttpContext.Request.Body.ReadAllBytes();
            var o    = Utilities.Serializer.Deserialize <JObject>(body);

            Trace.Assert(o != null, nameof(o) + " != null");

            // TODO: check object properties
            // e.g.: o.ContainsKey("method")

            if (o.ContainsKey("id"))
            {
                payload = o.ToObject <JsonRpcRequest>();
            }
            else
            {
                payload = o.ToObject <JsonRpcNotification>();
            }
        }
Example #4
0
        public Task ProcessRequestAsync(HttpContextPipelineHandlerContext context)
        {
            var isWebSocketRequest = context.HttpContext.Request.Headers.ValueEquals(HttpHeader.Upgrade, "websocket");

            if (!isWebSocketRequest)
            {
                return(Task.FromResult(0));
            }

            var webSocketKey      = context.HttpContext.Request.Headers[HttpHeader.SecWebSocketKey];
            var responseKey       = webSocketKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
            var responseKeyBuffer = Encoding.UTF8.GetBytes(responseKey);

            var hash = _sha1Computor(responseKeyBuffer);
            var secWebSocketAccept = Convert.ToBase64String(hash);

            context.HttpContext.Response.StatusCode = (int)HttpStatusCode.SwitchingProtocols;
            context.HttpContext.Response.Headers[HttpHeader.Connection]         = "Upgrade";
            context.HttpContext.Response.Headers[HttpHeader.Upgrade]            = "websocket";
            context.HttpContext.Response.Headers[HttpHeader.SecWebSocketAccept] = secWebSocketAccept;

            var webSocketSession = new WebSocketSession(context.HttpContext.ClientSession);

            context.HttpContext.ClientSession.SwitchProtocol(webSocketSession);

            _sessionCreated(webSocketSession);

            context.BreakPipeline = true;

            return(Task.FromResult(0));
        }
        public Task ProcessResponseAsync(HttpContextPipelineHandlerContext context)
        {
            var bodyLength = context.HttpContext.Response.Body?.Length ?? 0;

            context.HttpContext.Response.Headers[HttpHeader.ContentLength] = bodyLength.ToString(CultureInfo.InvariantCulture);

            return(Task.FromResult(0));
        }
Example #6
0
        public Task ProcessRequestAsync(HttpContextPipelineHandlerContext context)
        {
            ValidateRequestFormat(context, out var payload);

            var c = RpcSessionContext.Wrap(context);

            c.SaveRequestBody(payload);

            return(Task.FromResult(0));
        }
Example #7
0
        internal static RpcSessionContext Wrap([NotNull] HttpContextPipelineHandlerContext context)
        {
            var c = new RpcSessionContext(context);

            var request  = new RpcSessionRequest(c);
            var response = new RpcSessionResponse(c);

            c.Request  = request;
            c.Response = response;

            return(c);
        }
Example #8
0
        public Task ProcessRequestAsync(HttpContextPipelineHandlerContext context)
        {
            var originalHeaders = context.HttpContext.Request.Headers;
            var newHeaders      = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);

            foreach (var kv in originalHeaders)
            {
                newHeaders.Add(kv.Key, kv.Value);
            }

            context.HttpContext.Request.Headers = newHeaders;

            return(Task.FromResult(0));
        }
Example #9
0
        public Task ProcessRequestAsync(HttpContextPipelineHandlerContext context)
        {
            if (!context.HttpContext.Request.Uri.StartsWith(SERVICE_URI) || !context.HttpContext.Request.Method.Equals(HttpMethod.Post))
            {
                return(Task.CompletedTask);
            }

            var request  = JsonConvert.DeserializeObject <SmartHomeRequest>(new StreamReader(context.HttpContext.Request.Body).ReadToEnd());
            var response = DispatchHttpRequest(request);

            context.HttpContext.Response.Body       = new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(response)));
            context.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;

            return(Task.CompletedTask);
        }
Example #10
0
        public Task ProcessRequestAsync(HttpContextPipelineHandlerContext context)
        {
            var body = "<no body>";

            if (context.HttpContext.Request.Body != null)
            {
                using (var streamReader = new StreamReader(context.HttpContext.Request.Body, Encoding.UTF8, false, 1024, true))
                {
                    body = streamReader.ReadToEnd();
                }

                context.HttpContext.Request.Body.Position = 0;
            }

            HttpNetTrace.Verbose(nameof(TraceHandler), context.HttpContext.Request.Method + " " + context.HttpContext.Request.Uri + " " + body);
            return(Task.FromResult(0));
        }
Example #11
0
        public async Task ProcessRequestAsync(HttpContextPipelineHandlerContext context)
        {
            var bodyLength = 0;

            if (context.HttpContext.Request.Headers.TryGetValue(HttpHeader.ContentLength, out var v))
            {
                bodyLength = int.Parse(v);
            }

            if (bodyLength == 0)
            {
                context.HttpContext.Request.Body = new MemoryStream(0);
                return;
            }

            if (context.HttpContext.Request.Headers.ValueEquals(HttpHeader.Expect, "100-Continue"))
            {
                var response = new RawHttpResponse
                {
                    Version    = context.HttpContext.Request.Version,
                    StatusCode = (int)HttpStatusCode.Continue
                };

                await context.HttpContext.SessionHandler.ResponseWriter.WriteAsync(response, context.HttpContext.ClientSession.CancellationToken);
            }

            while (context.HttpContext.SessionHandler.RequestReader.BufferLength < bodyLength)
            {
                await context.HttpContext.SessionHandler.RequestReader.FetchChunk(context.HttpContext.ClientSession.CancellationToken);
            }

            context.HttpContext.Request.Body = new MemoryStream(bodyLength);
            for (var i = 0; i < bodyLength; i++)
            {
                context.HttpContext.Request.Body.WriteByte(context.HttpContext.SessionHandler.RequestReader.DequeueFromBuffer());
            }

            context.HttpContext.Request.Body.Position = 0;
        }
Example #12
0
        Task IHttpContextPipelineHandler.ProcessRequestAsync(HttpContextPipelineHandlerContext context)
        {
            var c        = RpcSessionContext.Wrap(context);
            var skeleton = c.GetRequestBodyAsJsonRpc();

            Trace.Assert(skeleton != null, nameof(skeleton) + " != null");

            var methodName = skeleton.Method;

            if (_routes.TryGetValue(methodName, out var handler))
            {
                Debug.Print("Found route: {0}", methodName);

                handler.Invoke(c);

                context.BreakPipeline = true;

                return(Task.FromResult(0));
            }

            Debug.Print("Registered route not found for method '{0}'", methodName);

            return(Task.FromException(new InvalidRpcRequestException($"Route not found for method '{methodName}'")));
        }
Example #13
0
 public Task ProcessResponseAsync(HttpContextPipelineHandlerContext context)
 {
     return(Task.FromResult(0));
 }
Example #14
0
 public Task ProcessResponseAsync(HttpContextPipelineHandlerContext context)
 {
     HttpNetTrace.Verbose(nameof(TraceHandler), context.HttpContext.Response.StatusCode + " " + context.HttpContext.Response.ReasonPhrase);
     return(Task.FromResult(0));
 }
Example #15
0
 public Task ProcessResponseAsync(HttpContextPipelineHandlerContext context) => Task.CompletedTask;
Example #16
0
 // ReSharper disable once NotNullMemberIsNotInitialized
 private RpcSessionContext([NotNull] HttpContextPipelineHandlerContext context)
 {
     RawContext = context;
 }