示例#1
0
        protected internal HttpRequest(HttpListenerRequest request)
        {
            Request  = request;
            PathInfo = RawUrl.Split(new[] { '?' }, 2)[0];
            Name     = $"{HttpMethod} {PathInfo}";
            Id       = Guid.NewGuid().Truncate();
            Advanced = new AdvancedHttpRequest(request);

            /*ContentEncoding = request.ContentEncoding;
             * if (request.ContentType == null)
             * {
             *  ContentEncoding = Encoding.UTF8;
             * }*/
            ContentEncoding = Encoding.UTF8;
            try
            {
                int index = request?.RawUrl?.IndexOf("?") ?? -1;
                if (index >= 0)
                {
                    QueryString = HttpUtility.ParseQueryString(Request.RawUrl.Substring(index + 1), ContentEncoding);
                }
            }
            catch
            {
                QueryString = request.QueryString;
            }
        }
示例#2
0
        /// <summary>
        /// Process URL path string.
        /// </summary>
        /// <param name="path"></param>
        public Url(string path)
        {
            _path          = path;
            ParameterCount = 0;

            // process url parameters
            string[] splitUrlQuestionMark = RawUrl.Split('?');

            // url contains one ? and is not empty or null before and after ?
            if (splitUrlQuestionMark.Length == 2 && !String.IsNullOrEmpty(splitUrlQuestionMark[0]) &&
                !String.IsNullOrEmpty(splitUrlQuestionMark[1]))
            {
                // split at & and remove fragments
                string[] splitUrlParams = splitUrlQuestionMark[1].Split("&");
                splitUrlParams[splitUrlParams.GetUpperBound(0)] = splitUrlParams.Last().Split("#").First();

                foreach (var param in splitUrlParams)
                {
                    string[] urlParams = param.Split("=");
                    if (urlParams.Length != 2)
                    {
                        break;
                    }
                    ParameterCount++;
                    Parameter[urlParams[0]] = urlParams[1];
                }
            }
        }
示例#3
0
 protected internal HttpRequest(Mono.Net.HttpListenerRequest request)
 {
     Request  = request;
     PathInfo = RawUrl.Split(new[] { '?' }, 2)[0];
     Name     = $"{HttpMethod} {PathInfo}";
     Id       = Guid.NewGuid().Truncate();
     Advanced = new AdvancedHttpRequest(request);
 }
示例#4
0
 protected internal HttpRequest(HttpListenerRequest request)
 {
     Request    = request;
     HttpMethod = (HttpMethod)Enum.Parse(typeof(HttpMethod), Request.HttpMethod);
     PathInfo   = RawUrl.Split(new[] { '?' }, 2)[0];
     Name       = $"{HttpMethod} {PathInfo}";
     Id         = Guid.NewGuid().Truncate();
     Advanced   = new AdvancedHttpRequest(request);
 }
示例#5
0
        internal HttpRequest(HttpListenerRequest request)
        {
            _request   = request;
            HttpMethod = (HttpMethod)Enum.Parse(typeof(HttpMethod), _request.HttpMethod);
            PathInfo   = (RawUrl.Split(new[] { '?' }, 2))[0];

            using (var reader = new StreamReader(_request.InputStream, _request.ContentEncoding))
            {
                Payload = reader.ReadToEnd();
            }
        }
示例#6
0
        private void SplitUrl()
        {
            //check for fragment first, because everything after the first # is a fragment
            if (RawUrl.Contains('#'))
            {
                var parts = RawUrl.Split("#", 2, StringSplitOptions.RemoveEmptyEntries);
                RawUrl    = parts[0]; //everything before the # belongs to the url
                _fragment = parts[1]; //everytihng after the # belongs to the fragment
            }

            //a valid url can be split into two parts
            var extracted = RawUrl.Split("?", 2, StringSplitOptions.RemoveEmptyEntries);

            if (!string.IsNullOrEmpty(extracted[0]))
            {
                //set the path
                var segmentsRaw = new ArrayList();
                foreach (var segment in extracted[0].Split("/", StringSplitOptions.RemoveEmptyEntries))
                {
                    segmentsRaw.Add(segment); //adds everything to the arraylist
                }
                var sb = new StringBuilder();
                if (segmentsRaw.Count > 0)
                {
                    foreach (string rawSegment in segmentsRaw.ToArray())
                    {
                        sb.Append("/");
                        sb.Append(rawSegment);
                    }
                }
                else
                {
                    sb.Append("/");  //no segments means root was requested
                }
                Path      = sb.ToString();
                _segments = sb.ToString().Split("/", StringSplitOptions.RemoveEmptyEntries);
            }

            if (extracted.Length > 1 && !string.IsNullOrEmpty(extracted[1]))
            {
                //these should be the parameters, which are separated by "&"
                var keyValuePairs = extracted[1].Split("&", StringSplitOptions.RemoveEmptyEntries);
                foreach (var pair in keyValuePairs)
                {
                    //name=flo
                    //age=20
                    //the key value pairs are seperated by "="
                    var keyValue =
                        pair.Split("=", 2, StringSplitOptions.RemoveEmptyEntries); //should only be 2 items
                    Parameter.Add(keyValue[0], keyValue[1]);
                }
            }
        }
示例#7
0
文件: WebServer.cs 项目: ghconn/mich
        private void DoParse()
        {
            string[] lines = _rawRequestHeaders.Split(new[] { "\r\n" }, StringSplitOptions.None);

            string[] action = lines[0].Split(' ');
            HttpMethod = action[0];
            RawUrl     = action[1];
            Protocol   = action[2];

            string[] path = RawUrl.Split('?');

            FilePath = HttpUtility.UrlDecode(path[0]);
            if (path.Length == 2)
            {
                QueryString = path[1];
            }

            Headers = new NameValueCollection();

            bool isCompletedHeader = false;

            for (var i = 1; i < lines.Length; i++)
            {
                var line = lines[i];

                if (string.IsNullOrEmpty(line))
                {
                    isCompletedHeader = true;
                    continue;
                }

                if (isCompletedHeader)
                {
                    //header后面是一个空白行,空白行后面所有内容是Body
                    Body = string.Join("\r\n", lines.Where((l, index) => index >= i));
                    break;
                }
                else
                {
                    int iSeparator = line.IndexOf(":");
                    Headers.Add(line.Substring(0, iSeparator), line.Remove(0, iSeparator + 1).TrimStart());
                }
            }
        }
示例#8
0
        private void DoParse()
        {
            string[] lines = _rawRequestHeaders.Split(new[] { "\r\n" }, StringSplitOptions.None);

            string[] actions = lines[0].Split(' ');
            HttpMethod = actions[0];
            RawUrl     = actions[1];
            Protocol   = actions[2];

            string[] path = RawUrl.Split('?');
            FilePath = HttpUtility.UrlDecode(path[0]);
            if (path.Length == 2)
            {
                QueryString = path[1];
            }

            Headers = new NameValueCollection();

            bool headerComplete = false;

            for (int i = 1; i < lines.Length; i++)
            {
                string line = lines[i];
                if (string.IsNullOrEmpty(line))
                {
                    headerComplete = true;
                    continue;
                }

                if (headerComplete)
                {
                    EntityBody = line;
                }
                else
                {
                    int separator = line.IndexOf(":");
                    Headers.Add(line.Substring(0, separator),
                                line.Substring(separator + 1, line.Length - separator - 1).TrimStart());
                }
            }
        }
示例#9
0
        private void DoParse()
        {
            string[] lines   = _rawRequestHeaders.Split(new[] { "\r\n" }, StringSplitOptions.None);
            string[] actions = lines[0].Split(' ');
            HttpMethod = actions[0];
            RawUrl     = actions[1];
            Protocol   = actions[2];

            string[] path = RawUrl.Split('?');
            if (path[0].IndexOf('.') == -1 && !path[0].EndsWith("/", StringComparison.Ordinal))
            {
                FilePath = HttpUtility.UrlDecode(path[0] + "/");
            }
            else
            {
                FilePath = HttpUtility.UrlDecode(path[0]);
            }
            if (path.Length == 2)
            {
                QueryString = path[1];
            }
            Headers = new Dictionary <string, string>();
            for (int i = 1; i < lines.Length; i++)
            {
                string line = lines[i];
                if (string.IsNullOrEmpty(line))
                {
                    break;
                }
                int separator = line.IndexOf(":");
                Headers.Add(line.Substring(0, separator),
                            line.Substring(separator + 1).TrimStart());
            }
            KeepAlive = Headers["Connection"] == null ? false : Headers["Connection"] == "keep-alive";
            GZip      = Headers["Accept-Encoding"] == null ? false : (Headers["Accept-Encoding"].IndexOf("gzip") != -1);
        }
示例#10
0
        public RushContext(HttpContext context)
        {
            this.HttpContext = context;

            HttpVerb verb = HttpVerb.Unsupported;

            Enum.TryParse(context.Request.RequestType, true, out verb);
            this.Verb = verb;

            this.RawUrl = context.Request.AppRelativeCurrentExecutionFilePath.Replace("~/", "");

            string[] segments = RawUrl.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
            if (segments.Length == 3)
            {
                this.Controller = segments[1] + "Controller";
                this.Resource   = segments[2];
            }
            if (segments.Length == 4)
            {
                this.Controller = segments[1] + "Controller";
                this.Resource   = segments[2];
                this.Id         = segments[3];
            }

            this.Headers = new Dictionary <string, string>();
            foreach (var key in context.Request.Headers.AllKeys)
            {
                this.Headers[key] = context.Request.Headers[key];
            }

            this.QueryString = new Dictionary <string, string>();
            foreach (var key in context.Request.QueryString.AllKeys)
            {
                this.QueryString[key] = context.Request.QueryString[key];
            }
        }
示例#11
0
        /// <summary>
        /// 构建http请求对象
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="size"></param>
        internal HttpRequest(Stream stream, int size)
        {
            handler = stream;
            bytes   = new byte[size];
            var data = GetRequestData(handler);
            var rows = Regex.Split(data, Environment.NewLine);

            //Request URL & Method & Version
            var first = Regex.Split(rows[0], @"(\s+)")
                        .Where(e => e.Trim() != string.Empty)
                        .ToArray();

            if (first.Length > 0)
            {
                switch (first[0])
                {
                case "GET": Method = HttpMethodType.GET; break;

                case "POST": Method = HttpMethodType.POST; break;

                case "PUT": Method = HttpMethodType.PUT; break;

                case "DELETE": Method = HttpMethodType.DELETE; break;

                case "HEAD": Method = HttpMethodType.HEAD; break;

                case "CONNECT": Method = HttpMethodType.CONNECT; break;

                case "OPTIONS": Method = HttpMethodType.OPTIONS; break;

                case "TRACE": Method = HttpMethodType.TRACE; break;

                default: Method = HttpMethodType.UNKNOWN; break;
                }
            }
            if (first.Length > 1)
            {
                RawUrl = Uri.UnescapeDataString(first[1]);
            }
            if (first.Length > 2)
            {
                ProtocolVersion = first[2];
            }

            // 判定是不是安全连接
            IsSSL = ProtocolVersion.ToLower().IndexOf("https") != -1;
            //Request Headers
            headers = GetRequestHeaders(rows);
            //Request Body
            Body = GetRequestBody(rows);
            var contentLength = GetHeader(RequestHeaders.ContentLength);

            if (int.TryParse(contentLength, out var length) && Body.Length != length)
            {
                do
                {
                    length = stream.Read(bytes, 0, bytes.Length);
                    Body  += Encoding.UTF8.GetString(bytes, 0, length);
                } while (Body.Length != length);
            }

            // 获取get数据
            if (RawUrl.Contains('?'))
            {
                GetValue  = RawUrl.Split('?')[1];
                GetParams = GetRequestParameters(GetValue);
            }
            else
            {
                GetParams = new Dictionary <string, string>();
            }

            // 获取消息体数据
            if (!string.IsNullOrEmpty(Body))
            {
                PostValue  = Body;
                PostParams = GetRequestParameters(PostValue);
            }
            else
            {
                PostParams = new Dictionary <string, string>();
            }
        }