예제 #1
0
        public ParsedCookie ParseCookie(RequestCookies aCookies)
        {
            var parsedCookie = new ParsedCookie();

            foreach (RequestCookie requestCookie in aCookies)
            {
                if (requestCookie.Name.Contains(CookieName) && requestCookie.Name.IndexOf('@') > -1 &&
                    requestCookie.Name.Substring(0, requestCookie.Name.IndexOf('@')) == _name)
                {
                    foreach (var subCookie in DecodeCookie(requestCookie.Value))
                    {
                        if (subCookie.Contains("__broker__"))
                        {
                            if (subCookie.IndexOf('=') > -1)
                            {
                                parsedCookie.ServerId = subCookie.Substring(subCookie.IndexOf('=') + 1);
                            }
                        }
                        else
                        {
                            if (parsedCookie.OriginalCookie != null)
                            {
                                parsedCookie.OriginalCookie += ';' + subCookie;
                            }
                            else
                            {
                                parsedCookie.OriginalCookie = subCookie;
                            }
                        }
                    }
                }
            }
            return(parsedCookie);
        }
예제 #2
0
 public void TestNullCookies()
 {
     RequestCookies cookies = new RequestCookies(null);
     Assert.Equal(0, cookies.Count);
     cookies = new RequestCookies(string.Empty);
     Assert.Equal(0, cookies.Count);
 }
예제 #3
0
        public void TestNullCookies()
        {
            RequestCookies cookies = new RequestCookies(null);

            Assert.Equal(0, cookies.Count);
            cookies = new RequestCookies(string.Empty);
            Assert.Equal(0, cookies.Count);
        }
예제 #4
0
 internal OwinRequest(OwinEnvironment owner)
 {
     env     = owner;
     Headers = new RequestHeaders(env);
     Query   = new RequestQuery(env);
     Cookies = new RequestCookies(env);
     Body    = env.Get <System.IO.Stream>(Owin.RequestBody);
 }
예제 #5
0
 public void TestCookies()
 {
     RequestCookies cookies = new RequestCookies("name     =   value; name1=value1;\r\nname2\r\n=\r\nvalue2;name3=value3");
     Assert.Equal("value", cookies["name"].Value);
     Assert.Equal("value1", cookies["name1"].Value);
     Assert.Equal("value2", cookies["name2"].Value);
     Assert.Equal("value3", cookies["name3"].Value);
     Assert.Null(cookies["notfound"]);
     cookies.Clear();
     Assert.Equal(0, cookies.Count);
 }
예제 #6
0
        public void SaveRule()
        {
            if (UnitTest.HttpRequestUnitTest == null)
            {
                var newHttpRequestUnitTest = new HttpRequestUnitTest
                {
                    UnitTestId = UnitTest.Id,
                    UnitTest   = UnitTest
                };
                UnitTest.HttpRequestUnitTest = newHttpRequestUnitTest;
            }

            var rule = UnitTest.HttpRequestUnitTest.Rules.FirstOrDefault();

            if (rule == null)
            {
                rule = new HttpRequestUnitTestRule()
                {
                    Id = Guid.NewGuid(),
                    HttpRequestUnitTest = UnitTest.HttpRequestUnitTest
                };
                UnitTest.HttpRequestUnitTest.Rules.Add(rule);
            }

            rule.DisplayName    = UnitTest.DisplayName;
            rule.SortNumber     = 0;
            rule.TimeoutSeconds = TimeOutSeconds;
            rule.Method         = Method;
            rule.Url            = new Uri(Url).AbsoluteUri;
            rule.ResponseCode   = ResponseCode;
            rule.SuccessHtml    = SuccessHtml;
            rule.ErrorHtml      = ErrorHtml;

            foreach (var data in rule.Datas.ToArray())
            {
                rule.Datas.Remove(data);
                AccountDbContext.Entry(data).State = System.Data.Entity.EntityState.Deleted;
            }

            if (RequestHeaders != null)
            {
                RequestHeaders.ForEach(x => AddRuleData(rule, x, HttpRequestUnitTestRuleDataType.RequestHeader));
            }

            if (RequestCookies != null)
            {
                RequestCookies.ForEach(x => AddRuleData(rule, x, HttpRequestUnitTestRuleDataType.RequestCookie));
            }

            if (WebFormDatas != null)
            {
                WebFormDatas.ForEach(x => AddRuleData(rule, x, HttpRequestUnitTestRuleDataType.WebFormData));
            }
        }
예제 #7
0
            public void DeserializesWhenCookieIsPresentAndValid()
            {
                RequestCookies.Add(new HttpCookie(CookieName, SerializedEnrollment));

                var result = RunTest(User);

                Assert.True(result, "The test should be enabled.");
                Assert.Empty(ResponseCookies.Keys.Cast <string>());
                EnrollmentFactory.Verify(x => x.Initialize(), Times.Never);
                EnrollmentFactory.Verify(x => x.Serialize(It.IsAny <ABTestEnrollment>()), Times.Never);
                EnrollmentFactory.Verify(x => x.TryDeserialize(It.IsAny <string>(), out OutEnrollment), Times.Once);
            }
예제 #8
0
        public void TestCookies()
        {
            RequestCookies cookies = new RequestCookies("name     =   value; name1=value1;\r\nname2\r\n=\r\nvalue2;name3=value3");

            Assert.Equal("value", cookies["name"].Value);
            Assert.Equal("value1", cookies["name1"].Value);
            Assert.Equal("value2", cookies["name2"].Value);
            Assert.Equal("value3", cookies["name3"].Value);
            Assert.Null(cookies["notfound"]);
            cookies.Clear();
            Assert.Equal(0, cookies.Count);
        }
예제 #9
0
        /// <summary>
        /// Prepares a string with cookie data for HTTP_COOKIE cgi variable.
        /// </summary>
        /// <param name="cookies"></param>
        /// <returns></returns>
        private static string GetCookieString(RequestCookies cookies)
        {
            StringBuilder cookie = new StringBuilder();

            foreach (RequestCookie c in cookies)
            {
                cookie.AppendFormat("{0}={1};", c.Name, c.Value);
            }

            string result = cookie.ToString();

            if (result.EndsWith(";"))
            {
                result = result.Substring(0, result.Length - 1);
            }

            return(result);
        }
예제 #10
0
            public void InitializesWhenCookieIsPresentAndInvalid()
            {
                RequestCookies.Add(new HttpCookie(CookieName, SerializedEnrollment));
                EnrollmentFactory
                .Setup(x => x.TryDeserialize(It.IsAny <string>(), out OutEnrollment))
                .Returns(false);

                var result = RunTest(User);

                Assert.True(result, "The test should be enabled.");
                Assert.Contains(CookieName, ResponseCookies.Keys.Cast <string>());
                var cookie = ResponseCookies[CookieName];

                VerifyCookie(cookie);
                EnrollmentFactory.Verify(x => x.Initialize(), Times.Once);
                EnrollmentFactory.Verify(x => x.Serialize(InitializedEnrollment), Times.Once);
                EnrollmentFactory.Verify(x => x.Serialize(It.IsAny <ABTestEnrollment>()), Times.Once);
                EnrollmentFactory.Verify(x => x.TryDeserialize(It.IsAny <string>(), out OutEnrollment), Times.Once);
            }
예제 #11
0
        private void RequestReceivedHandler(object sender, RequestEventArgs e)
        {
            IHttpClientContext context = (IHttpClientContext)sender;
            IHttpRequest       request = e.Request;

            IHttpResponse response = request.CreateResponse(context);

            // Load cookies if they exist
            RequestCookies cookies = (request.Headers["cookie"] != null)
                ? new RequestCookies(request.Headers["cookie"])
                : new RequestCookies(String.Empty);

            request.SetCookies(cookies);

            // Create a request signature
            HttpRequestSignature signature = new HttpRequestSignature(request);

            // Look for a signature match in our handlers
            HttpRequestHandler foundHandler = null;

            for (int i = 0; i < m_requestHandlers.Length; i++)
            {
                HttpRequestHandler handler = m_requestHandlers[i];

                if (signature == handler.Signature)
                {
                    foundHandler = handler;
                    break;
                }
            }

            if (foundHandler != null)
            {
                FireRequestCallback(context, request, response, foundHandler);
            }
            else
            {
                FireRequestCallback(context, request, response, m_notFoundHandler);
            }
        }
예제 #12
0
        public static ParsedHttpRequest ParseRawRequest(string raw, IgnoreHttpParserOptions options = null)
        {
            try
            {
                var lines = SplitLines(raw);

                var requestLine    = new RequestLine(lines);
                var requestHeaders = new RequestHeaders(lines);
                requestHeaders.AddHeader("Method", requestLine.Method);
                requestHeaders.AddHeader("HttpVersion", requestLine.HttpVersion);

                var requestCookies = new RequestCookies(lines);
                var requestBody    = new RequestBody(requestLine, lines);

                var parsed = new ParsedHttpRequest(options)
                {
                    Url         = requestLine.Url,
                    Uri         = new Uri(requestLine.Url),
                    Headers     = requestHeaders.Headers,
                    Cookies     = requestCookies.ParsedCookies,
                    RequestBody = requestBody.Body
                };

                parsed.ApplyIgnoreOptions();

                return(parsed);
            }
            catch (CouldNotParseHttpRequestException c)
            {
                Console.WriteLine($"Could not parse the raw request. {c.Message}");
                throw;
            }
            catch (Exception e)
            {
                Console.WriteLine($"Unhandled error parsing the raw request: {raw}\r\nError {e.Message}");
                throw;
            }
        }
예제 #13
0
 ///<summary>
 /// Cookies
 ///</summary>
 ///<param name="cookies">the cookies</param>
 public void SetCookies(RequestCookies cookies)
 {
   Cookies = cookies;
 }
예제 #14
0
 public void SetCookies(RequestCookies cookies)
 {
 }
예제 #15
0
 /// <summary>
 /// Sets the cookies.
 /// </summary>
 /// <param name="cookies">The cookies.</param>
 public void SetCookies(RequestCookies cookies)
 {
     _cookies = cookies;
 }
예제 #16
0
        public bool GetWebData()
        {
            if (string.IsNullOrEmpty(RequestUrl))
            {
                return(false);
            }

            Log.Debug("NaviX: Processor: Web Request");
            Log.Debug("NaviX: Processor:\t Action: {0}", Action);
            Log.Debug("NaviX: Processor:\t Url: {0}", RequestUrl);
            Log.Debug("NaviX: Processor:\t Referer: {0}", Referer);
            Log.Debug("NaviX: Processor:\t Cookies: {0}", RequestCookies);
            Log.Debug("NaviX: Processor:\t Method: {0}", Method);
            Log.Debug("NaviX: Processor:\t Useragent: {0}", UserAgent);
            Log.Debug("NaviX: Processor:\t Post Data: {0}", PostData);

            responseHeaders = new Dictionary <string, string>();
            responseCookies = new Dictionary <string, string>();

            try
            {
                Uri            uri     = new Uri(RequestUrl);
                HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
                if (request == null)
                {
                    return(false);
                }

                if (!string.IsNullOrEmpty(Referer))
                {
                    request.Referer = Referer;
                }
                if (!string.IsNullOrEmpty(UserAgent))
                {
                    request.UserAgent = UserAgent;
                }

                request.CookieContainer = new CookieContainer();
                if (!string.IsNullOrEmpty(RequestCookies))
                {
                    foreach (string cookie in RequestCookies.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        string[] cookKeyVal = cookie.Split('=');
                        if (cookKeyVal.Length > 1)
                        {
                            request.CookieContainer.Add(new Cookie(cookKeyVal[0].Trim(), cookKeyVal[1].Trim(), uri.AbsolutePath, uri.Host));
                        }
                    }
                }

                request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
                if (RequestHeaders != null)
                {
                    foreach (string header in RequestHeaders.Keys)
                    {
                        request.Headers[header] = RequestHeaders[header];
                    }
                }

                if (Action != null && Action.ToLower() == "headers")
                {
                    request.Method = "HEAD";
                }
                else if (Method != null && Method.ToLower() == "post")
                {
                    request.Method      = "POST";
                    request.ContentType = "application/x-www-form-urlencoded";
                    byte[] data = Encoding.UTF8.GetBytes(PostData);
                    request.ContentLength = data.Length;
                    using (System.IO.Stream requestStream = request.GetRequestStream())
                        requestStream.Write(data, 0, data.Length);
                }

                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    if (request.RequestUri.Equals(response.ResponseUri))
                    {
                        if (response.ContentLength > 0 && response.ContentLength < 1024)
                        {
                            getUrl = response.ResponseUri.ToString();
                        }
                        else
                        {
                            getUrl = RequestUrl;
                        }
                    }
                    else
                    {
                        getUrl = response.ResponseUri.OriginalString;
                    }

                    System.IO.Stream responseStream;
                    if (response.ContentEncoding.ToLower().Contains("gzip"))
                    {
                        responseStream = new System.IO.Compression.GZipStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress);
                    }
                    else if (response.ContentEncoding.ToLower().Contains("deflate"))
                    {
                        responseStream = new System.IO.Compression.DeflateStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress);
                    }
                    else
                    {
                        responseStream = response.GetResponseStream();
                    }

                    foreach (string s in response.Headers.AllKeys)
                    {
                        responseHeaders[s] = response.Headers[s];
                    }
                    foreach (Cookie cookie in response.Cookies)
                    {
                        responseCookies[cookie.Name] = cookie.Value;
                    }

                    Encoding responseEncoding = Encoding.UTF8;
                    if (!String.IsNullOrEmpty(response.CharacterSet.Trim()))
                    {
                        responseEncoding = Encoding.GetEncoding(response.CharacterSet.Trim(new char[] { ' ', '"' }));
                    }

                    using (System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, responseEncoding, true))
                        content = reader.ReadToEnd().Trim();
                }

                return(true);
            }
            catch (Exception ex)
            {
                Log.Warn("NaviXWebRequest: error - {0}\n{1}", ex.Message, ex.StackTrace);
                return(false);
            }
        }
예제 #17
0
        /// <summary>
        /// Prepares a string with cookie data for HTTP_COOKIE cgi variable.
        /// </summary>
        /// <param name="cookies"></param>
        /// <returns></returns>
        private static string GetCookieString(RequestCookies cookies)
        {
            StringBuilder cookie = new StringBuilder();

            foreach (RequestCookie c in cookies)
            {
                cookie.AppendFormat("{0}={1};", c.Name, c.Value);
            }

            string result = cookie.ToString();

            if (result.EndsWith(";"))
            {
                result = result.Substring(0, result.Length - 1);
            }

            return result;
        }
예제 #18
0
 public List <Cookie> GetRequestCookies()
 {
     return(RequestCookies.GetCookies(_url).Cast <Cookie>().ToList());
 }