Beispiel #1
0
        private async Task HandleClientRequest(HttpContext context)
        {
            HttpRequest  request  = context.Request;
            HttpResponse response = context.Response;

            if (shutdown)
            {
                response.StatusCode = 400; // BAD Request
                return;
            }

            try {
                if (request.Path == "/Mediator/" && context.WebSockets.IsWebSocketRequest)
                {
                    WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
                    await HandleClientWebSocket(webSocket);

                    return;
                }

                if (request.Method != "POST" || !HandleClientRequests.IsValid(request.Path))
                {
                    logger.Warn("Invalid request " + request.Path.ToUriComponent());
                    response.StatusCode = 400; // BAD Request
                    return;
                }

                //logger.Info("Client request: " + request.Path);

                JObject obj = null;
                using (var body = request.Body) {
                    using (var reader = new StreamReader(body, Encoding.UTF8)) {
                        obj = await StdJson.JObjectFromReaderAsync(reader);

                        //logger.Info("ReqStr: " + StdJson.ObjectToString(obj, true));
                    }
                }

                using (ReqResult result = await reqHandler.Handle(request.Path, obj)) {
                    //logger.Info(result.AsString());

                    response.StatusCode    = result.StatusCode;
                    response.ContentLength = result.Bytes.Length;
                    response.ContentType   = "application/json";

                    try {
                        await result.Bytes.CopyToAsync(response.Body);
                    }
                    catch (Exception) {
                        response.StatusCode = 500;
                    }
                }
            }
            catch (Exception exp) {
                response.StatusCode = 500;
                logger.Warn(exp.GetBaseException(), "Error handling client request");
            }
        }