Пример #1
0
        public void HandleRequest(HTTPServerRequest request, HTTPServerResponse response)
        {
            StreamReader reader = new StreamReader(request.GetRequestStream(), Encoding.UTF8);
            string       req    = reader.ReadToEnd();
            string       n      = request.Get("name");

            if (_writeLogDelegate != null)
            {
                _writeLogDelegate("Handling GUID request");
            }

            if (request.URI == "/")
            {
                /**
                 * In this example we'll write the body to a memorystream before
                 * we send the whole buffer to the response. This way the KeepAlive
                 * can stay true since the length of the body is known when the
                 * response header is sent.
                 **/
                using (MemoryStream ostr = new MemoryStream())
                {
                    using (TextWriter tw = new StreamWriter(ostr))
                    {
                        tw.WriteLine("<html>");
                        tw.WriteLine("<header><title>GUID Server</title></header>");
                        tw.WriteLine("<body>");
                        tw.WriteLine(Guid.NewGuid().ToString());
                        tw.WriteLine("</body>");
                        tw.WriteLine("</html>");
                    }

                    response.SendBuffer(ostr.ToArray(), "text/html");
                }
            }
            else
            {
                response.StatusAndReason = HTTPServerResponse.HTTPStatus.HTTP_NOT_FOUND;
                response.Send();
            }
        }
Пример #2
0
        private void HandleResponse(HTTPServerRequest request, HTTPServerResponse response)
        {
            //响应格式
            response.ContentType = "application/json;charset=utf-8";

            var pathAndQuery = request.URI.TrimStart('/');
            var array        = pathAndQuery.Split('?');
            var methodName   = array[0];
            var paramString  = array.Length > 1 ? array[1] : null;
            var callMethod   = caller.GetCaller(methodName);

            if (callMethod == null)
            {
                response.StatusAndReason = HTTPServerResponse.HTTPStatus.HTTP_NOT_FOUND;
                var error = new HttpServiceResult {
                    Message = string.Format("{0}【{1}】", response.Reason, methodName)
                };
                SendResponse(response, error);
                return;
            }
            else if (callMethod.HttpMethod == HttpMethod.POST && request.Method.ToUpper() == "GET")
            {
                response.StatusAndReason = HTTPServerResponse.HTTPStatus.HTTP_METHOD_NOT_ALLOWED;
                var error = new HttpServiceResult {
                    Message = response.Reason
                };
                SendResponse(response, error);
                return;
            }

            try
            {
                //调用方法
                NameValueCollection nvs = null;
                if (callMethod.HttpMethod == HttpMethod.GET)
                {
                    nvs = HttpUtility.ParseQueryString(paramString ?? string.Empty, Encoding.UTF8);
                }
                else
                {
                    //接收流内部数据
                    var stream = request.GetRequestStream();

                    //接收流内部数据
                    var    sr          = new StreamReader(stream, Encoding.UTF8);
                    string streamValue = sr.ReadToEnd();

                    //转换成NameValueCollection
                    nvs = ConvertCollection(streamValue);
                }

                if (callMethod.Authorized)
                {
                    if (!request.Has("X-AuthParameter"))
                    {
                        throw new AuthorizeException("Request header did not exist [X-AuthParameter] info.");
                    }
                    else
                    {
                        //调用认证的信息
                        nvs[callMethod.AuthParameter] = request.Get("X-AuthParameter");
                    }
                }

                //转换成JsonString
                var    parameters = ConvertJsonString(nvs);
                string jsonString = caller.CallMethod(methodName, parameters);

                if (callMethod.TypeString)
                {
                    //如果返回是字符串类型,则设置为文本返回
                    response.ContentType = "text/plain;charset=utf-8";

                    //转换成string类型
                    jsonString = SerializationManager.DeserializeJson <string>(jsonString);
                }

                SendResponse(response, jsonString);
            }
            catch (HTTPMessageException ex)
            {
                response.StatusAndReason = HTTPServerResponse.HTTPStatus.HTTP_EXPECTATION_FAILED;
                var error = new HttpServiceResult {
                    Message = string.Format("{0} - {1}", response.Reason, ex.Message)
                };
                SendResponse(response, error);
            }
            catch (Exception ex)
            {
                response.StatusAndReason = HTTPServerResponse.HTTPStatus.HTTP_BAD_REQUEST;
                var e     = ErrorHelper.GetInnerException(ex);
                var error = new HttpServiceResult {
                    Message = string.Format("{0} - {1}", e.GetType().Name, e.Message)
                };
                SendResponse(response, error);
            }
        }