private void RequestHandler(EventHttpRequest req)
        {
            ThreadPool.QueueUserWorkItem(_ =>
            {
                PreProcessRequest(req);
                var pairs = req.Uri.Split(new[] { '?' }, 2);
                var path  = Uri.UnescapeDataString(pairs[0]);
                var query = pairs.Length == 2 ? pairs[1] : string.Empty;
                var nreq  = CreateRequest(req.Method, path, req.Headers,
                                          RequestStream.FromStream(new MemoryStream(req.RequestBody)), "http", query, req.UserHostAddress);
                _engine.HandleRequest(
                    nreq,
                    ctx =>
                {
                    PostProcessNancyResponse(nreq, ctx.Response);

                    var ms = new MemoryStream();
                    ctx.Response.Contents(ms);
                    req.Respond((System.Net.HttpStatusCode)ctx.Response.StatusCode, ctx.Response.Headers, ms.ToArray());
                },
                    exception =>
                {
                    req.Respond(System.Net.HttpStatusCode.InternalServerError, new Dictionary <string, string>(), new byte[0]);
                    if (Error != null)
                    {
                        Error(this, new ErrorEventArgs(exception));
                    }
                    else
                    {
                        Console.WriteLine(exception);
                    }
                });
            });
        }
示例#2
0
        private void RequestHandler(EventHttpRequest req)
        {
            if (req.Uri == null)
            {
                req.Respond(System.Net.HttpStatusCode.BadRequest, new Dictionary <string, string>(), new byte[0]);
                return;
            }
            ThreadPool.QueueUserWorkItem(_ =>
            {
                Request nreq;
                try
                {
                    PreProcessRequest(req);
                    var pairs = req.Uri.Split(new[] { '?' }, 2);
                    var path  = Uri.UnescapeDataString(pairs[0]);
                    var query = pairs.Length == 2 ? pairs[1] : string.Empty;

                    nreq = CreateRequest(req.Method, req.Host, path, req.Headers,
                                         RequestStream.FromStream(new MemoryStream(req.RequestBody)), "http", query, req.UserHostAddress);
                }
                catch (Exception e)
                {
                    DoRespond(req, GetExceptionResponse(e));
                    return;
                }
                try
                {
                    _engine.HandleRequest(
                        nreq,
                        ctx =>
                    {
                        ResponseData resp;
                        try
                        {
                            var ms = new MemoryStream();
                            PostProcessNancyResponse(nreq, ctx.Response);
                            ctx.Response.Contents(ms);
                            resp = new ResponseData(ctx.Response.StatusCode, ms.ToArray(), ctx.Response.Headers);
                        }
                        catch (Exception e)
                        {
                            resp = GetExceptionResponse(e);
                        }
                        DoRespond(req, resp);
                    },
                        exception => DoRespond(req, GetExceptionResponse(exception)));
                }
                catch (Exception e)
                {
                    DoRespond(req, GetExceptionResponse(e));
                }
            });
        }
示例#3
0
        private void HandleRequest(EventHttpRequest req)
        {
            ThreadPool.QueueUserWorkItem(async _ =>
            {
                try
                {
                    var env = new Dictionary<string, object>();
                    env["owin.RequestBody"] = new MemoryStream(req.RequestBody);
                    env["owin.RequestHeaders"] = req.Headers.ToDictionary(x => x.Key, x => x.Value.ToArray(), StringComparer.OrdinalIgnoreCase);
                    env["owin.RequestMethod"] = req.Method;

                    var pairs = req.Uri.Split(new[] { '?' }, 2);
                    var path = Uri.UnescapeDataString(pairs[0]);
                    var query = pairs.Length == 2 ? pairs[1] : string.Empty;
                    env["owin.RequestPath"] = path;
                    env["owin.RequestPathBase"] = "/";
                    env["owin.RequestProtocol"] = "HTTP/1.0";
                    env["owin.RequestQueryString"] = query;
                    env["owin.RequestScheme"] = "http";

                    var response = new MemoryStream();
                    var headers = new Dictionary<string, string[]>();
                    env["owin.ResponseBody"] = response;
                    env["owin.ResponseHeaders"] = headers;
                    env["owin.ResponseStatusCode"] = 200;

                    await _app(env);
                    req.Respond((HttpStatusCode) (int) env["owin.ResponseStatusCode"],
                        headers.Where(k => k.Value.Length != 0).ToDictionary(x => x.Key, x => x.Value[0]),
                        response.ToArray());

                }
                catch (Exception e)
                {
                    req.Respond(HttpStatusCode.InternalServerError, new Dictionary<string, string>(),
                        Encoding.UTF8.GetBytes(e.ToString()));
                }

            });
        }
示例#4
0
        private void HandleRequest(EventHttpRequest req)
        {
            ThreadPool.QueueUserWorkItem(async _ =>
            {
                try
                {
                    var env = new Dictionary <string, object>();
                    env["owin.RequestBody"]    = new MemoryStream(req.RequestBody);
                    env["owin.RequestHeaders"] = req.Headers.ToDictionary(x => x.Key, x => x.Value.ToArray(), StringComparer.OrdinalIgnoreCase);
                    env["owin.RequestMethod"]  = req.Method;

                    var pairs = req.Uri.Split(new[] { '?' }, 2);
                    var path  = Uri.UnescapeDataString(pairs[0]);
                    var query = pairs.Length == 2 ? pairs[1] : string.Empty;
                    env["owin.RequestPath"]        = path;
                    env["owin.RequestPathBase"]    = "/";
                    env["owin.RequestProtocol"]    = "HTTP/1.0";
                    env["owin.RequestQueryString"] = query;
                    env["owin.RequestScheme"]      = "http";

                    var response                   = new MemoryStream();
                    var headers                    = new Dictionary <string, string[]>();
                    env["owin.ResponseBody"]       = response;
                    env["owin.ResponseHeaders"]    = headers;
                    env["owin.ResponseStatusCode"] = 200;

                    await _app(env);
                    req.Respond((HttpStatusCode)(int)env["owin.ResponseStatusCode"],
                                headers.Where(k => k.Value.Length != 0).ToDictionary(x => x.Key, x => x.Value[0]),
                                response.ToArray());
                }
                catch (Exception e)
                {
                    req.Respond(HttpStatusCode.InternalServerError, new Dictionary <string, string>(),
                                Encoding.UTF8.GetBytes(e.ToString()));
                }
            });
        }
示例#5
0
        private static void Handler(EventHttpRequest req)
        {
            var headers = new Dictionary <string, string>();
            var resp    = "Hello, World!";

            if (!req.Uri.Contains("plaintext"))
            {
                var sw = new StringWriter();
                Serializer.Serialize(sw, new { message = "Hello, World!" });
                resp = sw.ToString();
                headers["Content-Type"] = "application/json";
            }
            req.Respond(HttpStatusCode.OK, headers, Encoding.UTF8.GetBytes(resp));
        }
示例#6
0
 void DoRespond(EventHttpRequest req, ResponseData resp)
 {
     req.Respond((System.Net.HttpStatusCode)resp.Code, resp.Headers ?? new Dictionary <string, string>(),
                 resp.Data ?? new byte[0]);
 }
示例#7
0
    private void RequestHandler(EventHttpRequest req)
    {
        ThreadPool.QueueUserWorkItem(_ =>
        {
            var headers = new Dictionary <string, string>()
            {
                { "Content-Type", "application/json; charset=utf-8" }
            };
            var msg = "";

            JavaScriptSerializer json = new JavaScriptSerializer();

            // get the HTTP method, path and body of the request
            string method    = req.Method;
            string[] request = req.Uri.Trim('/').Split('/');
            string data      = Encoding.UTF8.GetString(req.RequestBody);
            Dictionary <string, object> input = json.Deserialize <Dictionary <string, object> >(data);

            // connect to the sql server database
            MySqlConnection link = new MySqlConnection("addr=localhost;uid=user;pwd=pass;database=dbname");
            link.Open();

            // retrieve the table and key from the path
            string table = Regex.Replace(request[0], "[^a-z0-9_]+", "");
            int key      = request.Length > 1 ? int.Parse(request[1]) : 0;

            // escape the columns from the input object
            string[] columns = input != null ? input.Keys.Select(i => Regex.Replace(i.ToString(), "[^a-z0-9_]+", "")).ToArray() : null;

            // build the SET part of the SQL command
            string set = input != null ? String.Join(", ", columns.Select(i => "`" + i + "`=@_" + i).ToArray()) : "";

            // create SQL based on HTTP method
            string sql = null;
            switch (method)
            {
            case "GET":
                sql = string.Format("select * from `{0}`" + (key > 0 ? " where `id`=@pk" : ""), table); break;

            case "PUT":
                sql = string.Format("update `{0}` set {1} where `id`=@pk", table, set); break;

            case "POST":
                sql = string.Format("insert into `{0}` set {1}; select last_insert_id()", table, set); break;

            case "DELETE":
                sql = string.Format("delete `{0}` where `id`=@pk", table); break;
            }

            // add parameters to command
            MySqlCommand command = new MySqlCommand(sql, link);
            if (input != null)
            {
                foreach (string c in columns)
                {
                    command.Parameters.AddWithValue("@_" + c, input[c]);
                }
            }
            if (key > 0)
            {
                command.Parameters.AddWithValue("@pk", key);
            }

            // print results, insert id or affected row count
            if (method == "GET")
            {
                MySqlDataReader reader = command.ExecuteReader();
                var fields             = new List <string> ();
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    fields.Add(reader.GetName(i));
                }
                if (key == 0)
                {
                    msg += "[";
                }
                bool first = true;
                while (reader.Read())
                {
                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        msg += ",";
                    }
                    Dictionary <string, object> row = new Dictionary <string, object> ();
                    foreach (var field in fields)
                    {
                        row.Add(field, reader [field]);
                    }
                    msg += json.Serialize((object)row);
                }
                if (key == 0)
                {
                    msg += "]";
                }
                reader.Close();
            }
            else if (method == "POST")
            {
                MySqlDataReader reader = command.ExecuteReader();
                reader.NextResult();
                reader.Read();
                msg += json.Serialize((object)reader.GetValue(0));
                reader.Close();
            }
            else
            {
                msg += json.Serialize((object)command.ExecuteNonQuery());
            }

            // close mysql connection
            link.Close();

            req.Respond(System.Net.HttpStatusCode.OK, headers, Encoding.UTF8.GetBytes(msg));
        });
    }