Ejemplo n.º 1
0
        public static void OnIncomingRequest(HttpListenerContext context)
        {
            if (context == null)
            {
                return;
            }
            HttpListenerRequest  request  = context.Request;
            HttpListenerResponse response = context.Response;

            if (IsDebugginMode)
            {
                String address = request.RemoteEndPoint.Address.ToString();
                String method  = request.HttpMethod;
                String host    = request.Url.Host;
                String path    = request.Url.AbsolutePath;
                Log.Write(String.Format("address: {0}, method: {1}, host: {2}, path: {3}", address, method, host, path));
            }
            if (Http.RequestIsAcceptable(request))
            {
                // разбор запроса
                Encoding enc  = Encoding.UTF8;
                String   body = null;
                using (StreamReader sr = new StreamReader(request.InputStream, enc))
                {
                    body = sr.ReadToEnd();
                }
                if (!String.IsNullOrWhiteSpace(body))
                {
                    if (IsDebugginMode)
                    {
                        Log.Write("Request.InputStream: " + body);
                    }
                    RequestPackage rqp = null;
                    switch (body[0])
                    {
                    case '<':
                        rqp = RequestPackage.ParseXml(body);
                        break;

                    case '{':
                        rqp = RequestPackage.ParseJson(body);
                        break;

                    default:
                        break;
                    }
                    if (rqp != null)
                    {
                        // исполнение запроса
                        ResponsePackage rsp = SqlServer.Exec(rqp);
                        // запись ответа
                        Byte[] buff = (rsp == null) ? new Byte[0] : rsp.ToXml(enc);
                        if (IsDebugginMode)
                        {
                            Log.Write("Response.OutputStream: " + enc.GetString(buff));
                        }
                        response.OutputStream.Write(buff, 0, buff.Length);
                    }
                    else
                    {
                        Log.Write("Непонятен формат запроса: " + body);
                    }
                }
                else
                {
                    Log.Write("Запрос пуст.");
                }
            }
            else
            {
                Log.Write("Запрос не прошел проверку.");
            }
        }