Beispiel #1
0
        public HttpResponse Process(HttpRequest req)
        {
            if (req == null)
            {
                throw new ArgumentNullException(nameof(req));
            }

            string filePath = req.RawUrlWithoutQuery;

            if (!String.IsNullOrEmpty(filePath) && filePath.StartsWith("/"))
            {
                filePath = filePath.Substring(1);
            }
            filePath = AppDomain.CurrentDomain.BaseDirectory + filePath;
            filePath = filePath.Replace("+", " ").Replace("%20", " ");

            string contentType = GetContentType(filePath);

            if (!File.Exists(filePath))
            {
                Logging.Log("ContentRouteProcessor unable to find " + filePath);
                return(Send404Response(req));
            }

            try
            {
                byte[] data = null;
                if (req.Method.ToLower().Equals("get"))
                {
                    data = File.ReadAllBytes(filePath);
                }
                return(new HttpResponse(req, true, 200, null, contentType, data, true));
            }
            catch (Exception e)
            {
                Logging.Log("ContentRouteProcessor error reading " + filePath + ": " + e.Message);
                return(Send500Response(req));
            }
        }
        private void AcceptConnections(CancellationToken token)
        {
            try
            {
                if (ListenerSsl)
                {
                    ListenerPrefix = "https://" + ListenerIp + ":" + ListenerPort + "/";
                }
                else
                {
                    ListenerPrefix = "http://" + ListenerIp + ":" + ListenerPort + "/";
                }
                Http.Prefixes.Add(ListenerPrefix);
                Http.Start();

                while (Http.IsListening)
                {
                    ThreadPool.QueueUserWorkItem((c) =>
                    {
                        if (token.IsCancellationRequested)
                        {
                            throw new OperationCanceledException();
                        }

                        var context = c as HttpListenerContext;

                        try
                        {
                            #region Populate-Http-Request-Object

                            HttpRequest currRequest = new HttpRequest(context);
                            if (currRequest == null)
                            {
                                Logging.Log("Unable to populate HTTP request object on thread ID " + Thread.CurrentThread.ManagedThreadId + ", returning 400");
                                SendResponse(
                                    context,
                                    currRequest,
                                    BuildErrorResponse(500, "Unable to parse your request.", null),
                                    WatsonCommon.AddToDict("content-type", "application/json", null),
                                    400);
                                return;
                            }

                            Logging.Log("Thread " + currRequest.ThreadId + " " + currRequest.SourceIp + ":" + currRequest.SourcePort + " " + currRequest.Method + " " + currRequest.RawUrlWithoutQuery);

                            #endregion

                            #region Process-OPTIONS-Request

                            if (currRequest.Method.ToLower().Trim().Contains("option") &&
                                OptionsRoute != null)
                            {
                                Logging.Log("Thread " + Thread.CurrentThread.ManagedThreadId + " OPTIONS request received");
                                OptionsProcessor(context, currRequest);
                                return;
                            }

                            #endregion

                            #region Send-to-Handler

                            if (DebugRestRequests)
                            {
                                Logging.Log(currRequest.ToString());
                            }

                            Task.Run(() =>
                            {
                                HttpResponse currResponse = null;
                                Func <HttpRequest, HttpResponse> handler = null;

                                #region Find-Route

                                if (currRequest.Method.ToLower().Equals("get") || currRequest.Method.ToLower().Equals("head"))
                                {
                                    if (ContentRoutes.Exists(currRequest.RawUrlWithoutQuery))
                                    {
                                        // content route found
                                        currResponse = ContentProcessor.Process(currRequest);
                                    }
                                }

                                if (currResponse == null)
                                {
                                    handler = StaticRoutes.Match(currRequest.Method, currRequest.RawUrlWithoutQuery);
                                    if (handler != null)
                                    {
                                        // static route found
                                        currResponse = handler(currRequest);
                                    }
                                    else
                                    {
                                        // no static route, check for dynamic route
                                        handler = DynamicRoutes.Match(currRequest.Method, currRequest.RawUrlWithoutQuery);
                                        if (handler != null)
                                        {
                                            // dynamic route found
                                            currResponse = handler(currRequest);
                                        }
                                        else
                                        {
                                            // process using default route
                                            currResponse = DefaultRouteProcessor(context, currRequest);
                                        }
                                    }
                                }

                                #endregion

                                #region Return

                                if (currResponse == null)
                                {
                                    Logging.Log("Null response from handler for " + currRequest.SourceIp + ":" + currRequest.SourcePort + " " + currRequest.Method + " " + currRequest.RawUrlWithoutQuery);
                                    SendResponse(
                                        context,
                                        currRequest,
                                        BuildErrorResponse(500, "Unable to generate response", null),
                                        WatsonCommon.AddToDict("content-type", "application/json", null),
                                        500);
                                    return;
                                }
                                else
                                {
                                    if (DebugRestResponses)
                                    {
                                        Logging.Log(currResponse.ToString());
                                    }

                                    Dictionary <string, string> headers = new Dictionary <string, string>();
                                    if (!String.IsNullOrEmpty(currResponse.ContentType))
                                    {
                                        headers.Add("content-type", currResponse.ContentType);
                                    }

                                    if (currResponse.Headers != null && currResponse.Headers.Count > 0)
                                    {
                                        foreach (KeyValuePair <string, string> curr in currResponse.Headers)
                                        {
                                            headers = WatsonCommon.AddToDict(curr.Key, curr.Value, headers);
                                        }
                                    }

                                    if (currResponse.RawResponse)
                                    {
                                        SendResponse(
                                            context,
                                            currRequest,
                                            currResponse.Data,
                                            headers,
                                            currResponse.StatusCode);
                                        return;
                                    }
                                    else
                                    {
                                        SendResponse(
                                            context,
                                            currRequest,
                                            currResponse.ToJsonBytes(),
                                            headers,
                                            currResponse.StatusCode);
                                        return;
                                    }
                                }

                                #endregion
                            });

                            #endregion
                        }
                        catch (Exception)
                        {
                        }
                        finally
                        {
                        }
                    }, Http.GetContext());
                }
            }
            catch (Exception eOuter)
            {
                Logging.LogException("AcceptConnections", eOuter);
                throw;
            }
            finally
            {
                Logging.Log("Exiting");
            }
        }