コード例 #1
0
        public async Task OnRequest(object sender, SessionEventArgs e)
        {
            //Console.WriteLine(e.WebSession.Request.Url);

            ////read request headers
            var requestHeaders = e.WebSession.Request.Headers;

            var method = e.WebSession.Request.Method.ToUpper();

            if ((method == "POST" || method == "PUT" || method == "PATCH"))
            {
                //Get/Set request body bytes
                byte[] bodyBytes = await e.GetRequestBody();

                e.SetRequestBody(bodyBytes);

                //Get/Set request body as string
                string bodyString = await e.GetRequestBodyAsString();

                e.SetRequestBodyString(bodyString);

                //store request
                //so that you can find it from response handler
                e.UserData = e.WebSession.Request;
            }

            if (this.OnHttpUrlRequested != null)
            {
                var requestEvent = new HttpRequestRaisedEventArgs(
                    e.WebSession.Request.Url,
                    e.WebSession.Request.IsHttps ? UrlScheme.Https : UrlScheme.Http,
                    e.WebSession.Request.Method);
                if (e.WebSession.Request.Headers != null)
                {
                    var cookies = "";

                    foreach (var hdr in e.WebSession.Request.Headers)
                    {
                        requestEvent.Request.Headers.Add(new Net.HttpHeader(hdr.Name, hdr.Value));

                        if (hdr.Name.ToLower() == "cookie")
                        {
                            cookies = hdr.Value;
                        }
                    }

                    var parsedCookieCollection = CookieParser.ParseRequestCookie(cookies);
                    foreach (var cookie in parsedCookieCollection)
                    {
                        requestEvent.Request.Cookies.Add(cookie);
                    }
                }

                this.OnHttpUrlRequested(this, requestEvent);
            }

            //To cancel a request with a custom HTML content
            //Filter URL
            //if (e.WebSession.Request.RequestUri.AbsoluteUri.Contains("googlezffdf.com"))
            //{
            //    e.Ok("<!DOCTYPE html>" +
            //          "<html><body><h1>" +
            //          "Website Blocked" +
            //          "</h1>" +
            //          "<p>Blocked by titanium web proxy.</p>" +
            //          "</body>" +
            //          "</html>");
            //}
            //Redirect example
            //if (e.WebSession.Request.RequestUri.AbsoluteUri.Contains("wikipedia.org"))
            //{
            //    e.Redirect("https://www.paypal.com");
            //}
        }