public bool IsMatch(RewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            try
            {
                if (IsDynamicMapping)
                {
                    RouteTable.Routes.Add("default", new Route { Url = "{controller}/{action}" });
                    ControllerBuilder.Current.SetControllerFactory(new DefaultControllerFactory());
                    ControllerBuilder.Current.DefaultNamespaces.Add("KyCMS.Web");

                    RouteData routeData = RouteTable.Routes.GetRouteData(HttpContext.Current);
                    if (null == routeData)
                    {
                        return false;
                    }
                    RequestContext requestContext = new RequestContext { RouteData = routeData, HttpContext = HttpContext.Current };
                    IHttpHandler handler = routeData.RouteHandler.GetHttpHandler(requestContext);
                    HttpContext.Current.RemapHandler(handler);

                    //System.Web.HttpContext.Current.Response.Write(System.Web.HttpContext.Current.Request.Url + "<br/>");
                    //System.Web.HttpContext.Current.Response.Write(context.Method + "<br/>");
                    //System.Web.HttpContext.Current.Response.Write(context.Location + "<br/>");
                    //System.Web.HttpContext.Current.Response.Write(context.MapPath(context.Expand(context.Location)) + "<br/>");
                }
                /*
                string filename = context.MapPath(context.Expand(_location));
                return File.Exists(filename) || Directory.Exists(filename);
                */
                return IsDynamicMapping;
            }
            catch
            {
                return false;
            }
        }
        private bool HandleDefaultDocument(RewriteContext context)
        {
            var uri = new Uri(_httpContext.RequestUrl, context.Location);
            var b = new UriBuilder(uri);
            b.Path += "/";
            uri = b.Uri;
            if (uri.Host == _httpContext.RequestUrl.Host)
            {
                string filename = _httpContext.MapPath(uri.AbsolutePath);
                if (Directory.Exists(filename))
                {
                    foreach (string document in _configuration.DefaultDocuments)
                    {
                        string pathName = Path.Combine(filename, document);
                        if (File.Exists(pathName))
                        {
                            context.Location = new Uri(uri, document).AbsolutePath;
                            return true;
                        }
                    }
                }
            }

            return false;
        }
        private void ProcessRules(RewriteContext context)
        {
            const int MaxRestart = 10; // Controls the number of restarts so we don't get into an infinite loop

            IList<IRewriteAction> rewriteRules = _configuration.Rules;
            int restarts = 0;
            for (int i = 0; i < rewriteRules.Count; i++)
            {
                // If the rule is conditional, ensure the conditions are met.
                var condition = rewriteRules[i] as IRewriteCondition;
                if (condition == null || condition.IsMatch(context))
                {
                    // Execute the action.
                    IRewriteAction action = rewriteRules[i];
                    RewriteProcessing processing = action.Execute(context);

                    // If the action is Stop, then break out of the processing loop
                    if (processing == RewriteProcessing.StopProcessing)
                    {
                        _configuration.Logger.Debug(MessageProvider.FormatString(Message.StoppingBecauseOfRule));
                        break;
                    }
                    else if (processing == RewriteProcessing.RestartProcessing)
                    {
                        _configuration.Logger.Debug(MessageProvider.FormatString(Message.RestartingBecauseOfRule));

                        // Restart from the first rule.
                        i = 0;

                        if (++restarts > MaxRestart)
                        {
                            throw new InvalidOperationException(MessageProvider.FormatString(Message.TooManyRestarts));
                        }
                    }
                }
            }
        }
        /// <summary>
        ///     Expands the given input based on the current context.
        /// </summary>
        /// <param name="context">The current context</param>
        /// <param name="input">The input to expand.</param>
        /// <returns>The expanded input</returns>
        public string Expand(RewriteContext context, string input)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            /* replacement :- $n
                         * |	${[a-zA-Z0-9\-]+}
                         * |	${fn( <replacement> )}
                         * |	${<replacement-or-id>:<replacement-or-value>:<replacement-or-value>}
                         * 
                         * replacement-or-id :- <replacement> | <id>
                         * replacement-or-value :- <replacement> | <value>
                         */

            /* $1 - regex replacement
             * ${propertyname}
             * ${map-name:value}				map-name is replacement, value is replacement
             * ${map-name:value|default-value}	map-name is replacement, value is replacement, default-value is replacement
             * ${fn(value)}						value is replacement
             */

            using (var reader = new StringReader(input))
            {
                using (var writer = new StringWriter())
                {
                    var ch = (char) reader.Read();
                    while (ch != EndChar)
                    {
                        if (ch == '$')
                        {
                            writer.Write(Reduce(context, reader));
                        }
                        else
                        {
                            writer.Write(ch);
                        }

                        ch = (char) reader.Read();
                    }

                    return writer.GetStringBuilder().ToString();
                }
            }
        }
        /// <summary>
        /// Performs the rewriting.
        /// </summary>
        public void Rewrite()
        {
            string originalUrl = ContextFacade.GetRawUrl().Replace("+", " ");

            RawUrl = originalUrl;

            // Create the context
            RewriteContext context = new RewriteContext(this, originalUrl,
                                                        ContextFacade.GetHttpMethod(), ContextFacade.MapPath,
                                                        ContextFacade.GetServerVariables(), ContextFacade.GetHeaders(), ContextFacade.GetCookies());

            // Process each rule.
            ProcessRules(context);

            // Append any headers defined.
            AppendHeaders(context);

            // Append any cookies defined.
            AppendCookies(context);

            //var mobilePath = VirtualPathUtility.AppendTrailingSlash(HttpContext.Current.Request.ApplicationPath) + "Mobile/";
            //if (context.Location.Contains(mobilePath))
            //{
            //    if (!HttpContext.Current.Request.Browser.IsMobileDevice)
            //    {
            //        context.Location = VirtualPathUtility.AppendTrailingSlash(HttpContext.Current.Request.ApplicationPath) + "MobileAccess.html";
            //    }
            //}

            // Rewrite the path if the location has changed.
            ContextFacade.SetStatusCode((int)context.StatusCode);
            if ((context.Location != originalUrl) && ((int)context.StatusCode < 400))
            {
                if ((int)context.StatusCode < 300)
                {
                    // Successful status if less than 300
                    _configuration.Logger.Info(MessageProvider.FormatString(Message.RewritingXtoY,
                                                                            ContextFacade.GetRawUrl(), context.Location));

                    // Verify that the url exists on this server.
                    HandleDefaultDocument(context);// VerifyResultExists(context);

                    ContextFacade.RewritePath(context.Location);
                }
                else
                {
                    // Redirection
                    _configuration.Logger.Info(MessageProvider.FormatString(Message.RedirectingXtoY,
                                                                            ContextFacade.GetRawUrl(), context.Location));

                    ContextFacade.SetRedirectLocation(context.Location);
                }
            }
            else if ((int)context.StatusCode >= 400)
            {
                HandleError(context);
            }
            else if (HandleDefaultDocument(context))
            {
                ContextFacade.RewritePath(context.Location);
            }

            // Sets the context items.
            SetContextItems(context);
        }
        private string Reduce(RewriteContext context, StringReader reader)
        {
            string result;
            char   ch = (char)reader.Read();

            if (char.IsDigit(ch))
            {
                string num = ch.ToString();
                if (char.IsDigit((char)reader.Peek()))
                {
                    ch   = (char)reader.Read();
                    num += ch.ToString();
                }
                if (context.LastMatch != null)
                {
                    Group group = context.LastMatch.Groups[Convert.ToInt32(num)];

                    result = @group != null ? @group.Value : string.Empty;
                }
                else
                {
                    result = string.Empty;
                }
            }
            else
            {
                switch (ch)
                {
                case '<':
                {
                    string expr;

                    using (StringWriter writer = new StringWriter())
                    {
                        ch = (char)reader.Read();
                        while (ch != '>' && ch != (char)65535)
                        {
                            if (ch == '$')
                            {
                                writer.Write(this.Reduce(context, reader));
                            }
                            else
                            {
                                writer.Write(ch);
                            }
                            ch = (char)reader.Read();
                        }

                        expr = writer.GetStringBuilder().ToString();
                    }

                    if (context.LastMatch != null)
                    {
                        Group group = context.LastMatch.Groups[expr];
                        if (@group != null)
                        {
                            result = @group.Value;
                        }
                        else
                        {
                            result = string.Empty;
                        }
                    }
                    else
                    {
                        result = string.Empty;
                    }
                }
                break;

                case '{':
                {
                    string expr;
                    bool   isMap      = false;
                    bool   isFunction = false;

                    using (StringWriter writer = new StringWriter())
                    {
                        ch = (char)reader.Read();
                        while (ch != '}' && ch != (char)65535)
                        {
                            if (ch == '$')
                            {
                                writer.Write(this.Reduce(context, reader));
                            }
                            else
                            {
                                if (ch == ':')
                                {
                                    isMap = true;
                                }
                                else if (ch == '(')
                                {
                                    isFunction = true;
                                }
                                writer.Write(ch);
                            }
                            ch = (char)reader.Read();
                        }

                        expr = writer.GetStringBuilder().ToString();
                    }

                    if (isMap)
                    {
                        Match  match       = Regex.Match(expr, @"^([^\:]+)\:([^\|]+)(\|(.+))?$");
                        string mapName     = match.Groups[1].Value;
                        string mapArgument = match.Groups[2].Value;
                        string mapDefault  = match.Groups[4].Value;
                        result =
                            this._configuration.TransformFactory.GetTransform(mapName).ApplyTransform(
                                mapArgument) ?? mapDefault;
                    }
                    else if (isFunction)
                    {
                        Match             match            = Regex.Match(expr, @"^([^\(]+)\((.+)\)$");
                        string            functionName     = match.Groups[1].Value;
                        string            functionArgument = match.Groups[2].Value;
                        IRewriteTransform tx = this._configuration.TransformFactory.GetTransform(functionName);

                        result = tx != null?tx.ApplyTransform(functionArgument) : expr;
                    }
                    else
                    {
                        result = context.Properties[expr];
                    }
                }
                break;

                default:
                    result = ch.ToString();
                    break;
                }
            }

            return(result);
        }
        private void SetContextItems(RewriteContext context)
        {
            OriginalQueryString = new Uri(_httpContext.RequestUrl, _httpContext.RawUrl).Query.Replace("?", "");
            QueryString = new Uri(_httpContext.RequestUrl, context.Location).Query.Replace("?", "");

            // Add in the properties as context items, so these will be accessible to the handler
            foreach (string key in context.Properties.Keys)
            {
                _httpContext.SetItem(String.Format("Rewriter.{0}", key), context.Properties[key]);
            }
        }
 private void AppendHeaders(RewriteContext context)
 {
     foreach (string headerKey in context.ResponseHeaders)
     {
         _httpContext.SetResponseHeader(headerKey, context.ResponseHeaders[headerKey]);
     }
 }
Beispiel #9
0
 private void AppendCookies(RewriteContext context)
 {
     for (int i = 0; i < context.Cookies.Count; i++)
     {
         HttpCookie cookie = context.Cookies[i];
         ContextFacade.AppendCookie(cookie);
     }
 }
Beispiel #10
0
 private void AppendHeaders(RewriteContext context)
 {
     foreach (string headerKey in context.Headers)
     {
         ContextFacade.AppendHeader(headerKey, context.Headers[headerKey]);
     }
 }
Beispiel #11
0
 private void VerifyResultExists(RewriteContext context)
 {
     if ((String.Compare(context.Location, ContextFacade.GetRawUrl()) != 0) && ((int)context.StatusCode < 300))
     {
         Uri uri = new Uri(ContextFacade.GetRequestUrl(), context.Location);
         if (uri.Host == ContextFacade.GetRequestUrl().Host)
         {
             string filename = ContextFacade.MapPath(uri.AbsolutePath);
             if (!File.Exists(filename))
             {
                 _configuration.Logger.Debug(MessageProvider.FormatString(Message.ResultNotFound, filename));
                 context.StatusCode = HttpStatusCode.NotFound;
             }
             else
             {
                 HandleDefaultDocument(context);
             }
         }
     }
 }
Beispiel #12
0
        /// <summary>
        /// Handles the default document.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        private bool HandleDefaultDocument(RewriteContext context)
        {
            Uri uri = new Uri(this.ContextFacade.GetRequestUrl(), context.Location);
            UriBuilder b = new UriBuilder(uri);
            b.Path += "/";
            uri = b.Uri;
            if (uri.Host == this.ContextFacade.GetRequestUrl().Host)
            {
                try
                {
                    string filename = this.ContextFacade.MapPath(uri.AbsolutePath);

                    if (Directory.Exists(filename))
                    {
                        foreach (
                            string document in from string document in RewriterConfiguration.Current.DefaultDocuments
                                               let pathName = Path.Combine(filename, document)
                                               where File.Exists(pathName)
                                               select document)
                        {
                            context.Location = new Uri(uri, document).AbsolutePath;
                            return true;
                        }
                    }
                }
                catch (PathTooLongException)
                {
                    // ignore if path to long
                    return false;
                }
            }

            return false;
        }
Beispiel #13
0
        private bool HandleDefaultDocument(RewriteContext context)
        {
            Uri uri = new Uri(ContextFacade.GetRequestUrl(), context.Location);
            UriBuilder b = new UriBuilder(uri);
            b.Path += "/";
            uri = b.Uri;
            if (uri.Host == ContextFacade.GetRequestUrl().Host)
            {
                string filename = ContextFacade.MapPath(uri.AbsolutePath);
                if (Directory.Exists(filename))
                {
                    foreach (string document in RewriterConfiguration.Current.DefaultDocuments)
                    {
                        string pathName = Path.Combine(filename, document);
                        if (File.Exists(pathName))
                        {
                            context.Location = new Uri(uri, document).AbsolutePath;
                            return true;
                        }
                    }
                }
            }

            return false;
        }
Beispiel #14
0
        /// <summary>
        /// Performs the rewriting.
        /// </summary>
        public void Rewrite()
        {
            string originalUrl = ContextFacade.GetRawUrl().Replace("+", " ");
            RawUrl = originalUrl;

            // Create the context
            RewriteContext context = new RewriteContext(this, originalUrl,
                ContextFacade.GetHttpMethod(), ContextFacade.MapPath,
                ContextFacade.GetServerVariables(), ContextFacade.GetHeaders(), ContextFacade.GetCookies());

            // Process each rule.
            ProcessRules(context);

            // Append any headers defined.
            AppendHeaders(context);

            // Append any cookies defined.
            AppendCookies(context);

            // Rewrite the path if the location has changed.
            ContextFacade.SetStatusCode((int)context.StatusCode);
            if ((context.Location != originalUrl) && ((int)context.StatusCode < 400))
            {
                if ((int)context.StatusCode < 300)
                {
                    // Successful status if less than 300
                    _configuration.Logger.Info(MessageProvider.FormatString(Message.RewritingXtoY,
                        ContextFacade.GetRawUrl(), context.Location));

                    // Verify that the url exists on this server.
                    HandleDefaultDocument(context);// VerifyResultExists(context);

                    ContextFacade.RewritePath(context.Location);
                }
                else
                {
                    // Redirection
                    _configuration.Logger.Info(MessageProvider.FormatString(Message.RedirectingXtoY,
                        ContextFacade.GetRawUrl(), context.Location));

                    ContextFacade.SetRedirectLocation(context.Location);
                }
            }
            else if ((int)context.StatusCode >= 400)
            {
                HandleError(context);
            }
            else if (HandleDefaultDocument(context))
            {
                ContextFacade.RewritePath(context.Location);
            }

            // Sets the context items.
            SetContextItems(context);
        }
Beispiel #15
0
 public RewriteProcessing Execute(RewriteContext context)
 {
     context.StatusCode = StatusCode;
     return Processing;
 }
 private void VerifyResultExists(RewriteContext context)
 {
     if ((System.String.CompareOrdinal(context.Location, _httpContext.RawUrl) != 0) &&
         ((int) context.StatusCode < 300))
     {
         var uri = new Uri(_httpContext.RequestUrl, context.Location);
         if (uri.Host == _httpContext.RequestUrl.Host)
         {
             string filename = _httpContext.MapPath(uri.AbsolutePath);
             if (!File.Exists(filename))
             {
                 _configuration.Logger.Debug(MessageProvider.FormatString(Message.ResultNotFound, filename));
                 context.StatusCode = HttpStatusCode.NotFound;
             }
             else
             {
                 HandleDefaultDocument(context);
             }
         }
     }
 }
        private void HandleError(RewriteContext context)
        {
            // Return the status code.
            _httpContext.SetStatusCode((int) context.StatusCode);

            // Get the error handler if there is one.
            if (_configuration.ErrorHandlers.ContainsKey((int) context.StatusCode))
            {
                IRewriteErrorHandler handler = _configuration.ErrorHandlers[(int) context.StatusCode];

                try
                {
                    _configuration.Logger.Debug(MessageProvider.FormatString(Message.CallingErrorHandler));

                    // Execute the error handler.
                    _httpContext.HandleError(handler);
                }
                catch (HttpException)
                {
                    throw;
                }
                catch (Exception exc)
                {
                    _configuration.Logger.Fatal(exc.Message, exc);
                    throw new HttpException((int) HttpStatusCode.InternalServerError,
                                            HttpStatusCode.InternalServerError.ToString());
                }
            }
            else
            {
                throw new HttpException((int) context.StatusCode, context.StatusCode.ToString());
            }
        }
Beispiel #18
0
        private void SetContextItems(RewriteContext context)
        {
            this.OriginalQueryString =
                new Uri(this.ContextFacade.GetRequestUrl(), this.ContextFacade.GetRawUrl()).Query.Replace("?", string.Empty);

            this.QueryString = new Uri(this.ContextFacade.GetRequestUrl(), context.Location).Query.Replace("?", string.Empty);

            // Add in the properties as context items, so these will be accessible to the handler
            foreach (string key in context.Properties.Keys)
            {
                ContextFacade.SetItem(string.Format("Rewriter.{0}", key), context.Properties[key]);
            }
        }
 private void AppendCookies(RewriteContext context)
 {
     for (int i = 0; i < context.ResponseCookies.Count; i++)
     {
         _httpContext.SetResponseCookie(context.ResponseCookies[i]);
     }
 }
Beispiel #20
0
        private string Reduce(RewriteContext context, StringReader reader)
        {
            string result;
            char ch = (char)reader.Read();
            if (char.IsDigit(ch))
            {
                string num = ch.ToString();
                if (char.IsDigit((char)reader.Peek()))
                {
                    ch = (char)reader.Read();
                    num += ch.ToString();
                }
                if (context.LastMatch != null)
                {
                    Group group = context.LastMatch.Groups[Convert.ToInt32(num)];

                    result = @group != null ? @group.Value : string.Empty;
                }
                else
                {
                    result = string.Empty;
                }
            }
            else
                switch (ch)
                {
                    case '<':
                        {
                            string expr;

                            using (StringWriter writer = new StringWriter())
                            {
                                ch = (char)reader.Read();
                                while (ch != '>' && ch != (char)65535)
                                {
                                    if (ch == '$')
                                    {
                                        writer.Write(this.Reduce(context, reader));
                                    }
                                    else
                                    {
                                        writer.Write(ch);
                                    }
                                    ch = (char)reader.Read();
                                }

                                expr = writer.GetStringBuilder().ToString();
                            }

                            if (context.LastMatch != null)
                            {
                                Group group = context.LastMatch.Groups[expr];
                                if (@group != null)
                                {
                                    result = @group.Value;
                                }
                                else
                                {
                                    result = string.Empty;
                                }
                            }
                            else
                            {
                                result = string.Empty;
                            }
                        }
                        break;
                    case '{':
                        {
                            string expr;
                            bool isMap = false;
                            bool isFunction = false;

                            using (StringWriter writer = new StringWriter())
                            {
                                ch = (char)reader.Read();
                                while (ch != '}' && ch != (char)65535)
                                {
                                    if (ch == '$')
                                    {
                                        writer.Write(this.Reduce(context, reader));
                                    }
                                    else
                                    {
                                        if (ch == ':') isMap = true;
                                        else if (ch == '(') isFunction = true;
                                        writer.Write(ch);
                                    }
                                    ch = (char)reader.Read();
                                }

                                expr = writer.GetStringBuilder().ToString();
                            }

                            if (isMap)
                            {
                                Match match = Regex.Match(expr, @"^([^\:]+)\:([^\|]+)(\|(.+))?$");
                                string mapName = match.Groups[1].Value;
                                string mapArgument = match.Groups[2].Value;
                                string mapDefault = match.Groups[4].Value;
                                result =
                                    this._configuration.TransformFactory.GetTransform(mapName).ApplyTransform(
                                        mapArgument) ?? mapDefault;
                            }
                            else if (isFunction)
                            {
                                Match match = Regex.Match(expr, @"^([^\(]+)\((.+)\)$");
                                string functionName = match.Groups[1].Value;
                                string functionArgument = match.Groups[2].Value;
                                IRewriteTransform tx = this._configuration.TransformFactory.GetTransform(functionName);

                                result = tx != null ? tx.ApplyTransform(functionArgument) : expr;
                            }
                            else
                            {
                                result = context.Properties[expr];
                            }
                        }
                        break;
                    default:
                        result = ch.ToString();
                        break;
                }

            return result;
        }
        private string Reduce(RewriteContext context, StringReader reader)
        {
            string result;
            var ch = (char) reader.Read();
            if (Char.IsDigit(ch))
            {
                string num = ch.ToString(CultureInfo.InvariantCulture);
                if (Char.IsDigit((char) reader.Peek()))
                {
                    ch = (char) reader.Read();
                    num += ch.ToString(CultureInfo.InvariantCulture);
                }
                if (context.LastMatch != null)
                {
                    Group group = context.LastMatch.Groups[Convert.ToInt32(num)];
                    result = (group == null) ? String.Empty : group.Value;
                }
                else
                {
                    result = String.Empty;
                }
            }
            else if (ch == '<')
            {
                string expr;

                using (var writer = new StringWriter())
                {
                    ch = (char) reader.Read();
                    while (ch != '>' && ch != EndChar)
                    {
                        if (ch == '$')
                        {
                            writer.Write(Reduce(context, reader));
                        }
                        else
                        {
                            writer.Write(ch);
                        }
                        ch = (char) reader.Read();
                    }

                    expr = writer.GetStringBuilder().ToString();
                }

                if (context.LastMatch != null)
                {
                    Group group = context.LastMatch.Groups[expr];
                    result = (group == null) ? String.Empty : group.Value;
                }
                else
                {
                    result = String.Empty;
                }
            }
            else if (ch == '{')
            {
                string expr;
                bool isMap = false;
                bool isFunction = false;

                using (var writer = new StringWriter())
                {
                    ch = (char) reader.Read();
                    while (ch != '}' && ch != EndChar)
                    {
                        if (ch == '$')
                        {
                            writer.Write(Reduce(context, reader));
                        }
                        else
                        {
                            if (ch == ':') isMap = true;
                            else if (ch == '(') isFunction = true;
                            writer.Write(ch);
                        }
                        ch = (char) reader.Read();
                    }

                    expr = writer.GetStringBuilder().ToString();
                }

                if (isMap)
                {
                    Match match = Regex.Match(expr, @"^([^\:]+)\:([^\|]+)(\|(.+))?$");
                    string mapName = match.Groups[1].Value;
                    string mapArgument = match.Groups[2].Value;
                    string mapDefault = match.Groups[4].Value;
                    result = _configuration.TransformFactory.GetTransform(mapName).ApplyTransform(mapArgument);
                    if (result == null)
                    {
                        result = mapDefault;
                    }
                }
                else if (isFunction)
                {
                    Match match = Regex.Match(expr, @"^([^\(]+)\((.+)\)$");
                    string functionName = match.Groups[1].Value;
                    string functionArgument = match.Groups[2].Value;
                    IRewriteTransform tx = _configuration.TransformFactory.GetTransform(functionName);
                    result = (tx == null) ? expr : tx.ApplyTransform(functionArgument);
                }
                else
                {
                    result = context.Properties[expr];
                }
            }
            else
            {
                result = ch.ToString(CultureInfo.InvariantCulture);
            }

            return result;
        }
Beispiel #22
0
        /// <summary>
        /// Performs the rewriting.
        /// </summary>
        public void Rewrite()
        {
            string originalUrl = ContextFacade.GetRawUrl().Replace("+", " ");
            RawUrl = originalUrl;

            // Create the context
            RewriteContext context = new RewriteContext(
                this,
                originalUrl,
                ContextFacade.GetHttpMethod(),
                ContextFacade.MapPath,
                ContextFacade.GetServerVariables(),
                ContextFacade.GetHeaders(),
                ContextFacade.GetCookies());

            // Process each rule.
            ProcessRules(context);

            // Append any headers defined.
            AppendHeaders(context);

            // Append any cookies defined.
            AppendCookies(context);

            // Rewrite the path if the location has changed.
            ContextFacade.SetStatusCode((int)context.StatusCode);
            if ((context.Location != originalUrl) && ((int)context.StatusCode < 400))
            {
                if ((int)context.StatusCode < 300)
                {
                    // Successful status if less than 300
                    _configuration.Logger.Info(
                        MessageProvider.FormatString(Message.RewritingXtoY, ContextFacade.GetRawUrl(), context.Location));

                    // Verify that the url exists on this server.
                    HandleDefaultDocument(context); // VerifyResultExists(context);

                    if (context.Location.Contains(@"&"))
                    {
                        var queryStringCollection = HttpUtility.ParseQueryString(new Uri(this.ContextFacade.GetRequestUrl(), context.Location).Query);

                        StringBuilder builder = new StringBuilder();
                        foreach (string value in queryStringCollection.AllKeys.Distinct())
                        {
                            builder.AppendFormat("{0}={1}&", value, queryStringCollection.GetValues(value).FirstOrDefault());
                        }

                        context.Location = context.Location.Remove(context.Location.IndexOf("?") + 1);
                        context.Location = context.Location + builder;

                        if (context.Location.EndsWith(@"&"))
                        {
                            context.Location = context.Location.Remove(context.Location.Length - 1);
                        }
                    }

                    ContextFacade.RewritePath(context.Location);
                }
                else
                {
                    // Redirection
                    _configuration.Logger.Info(
                        MessageProvider.FormatString(
                            Message.RedirectingXtoY, ContextFacade.GetRawUrl(), context.Location));

                    ContextFacade.SetRedirectLocation(context.Location);
                }
            }
            else if ((int)context.StatusCode >= 400)
            {
                HandleError(context);
            }
            else if (HandleDefaultDocument(context))
            {
                ContextFacade.RewritePath(context.Location);
            }

            // Sets the context items.
            SetContextItems(context);
        }
        /// <summary>
        /// Performs the rewriting.
        /// </summary>
        public void Rewrite()
        {
            string originalUrl = ContextFacade.GetRawUrl().Replace("+", " ");

            RawUrl = originalUrl;

            // Create the context
            RewriteContext context = new RewriteContext(
                this,
                originalUrl,
                ContextFacade.GetHttpMethod(),
                ContextFacade.MapPath,
                ContextFacade.GetServerVariables(),
                ContextFacade.GetHeaders(),
                ContextFacade.GetCookies());

            // Process each rule.
            ProcessRules(context);

            // Append any headers defined.
            AppendHeaders(context);

            // Append any cookies defined.
            AppendCookies(context);

            // Rewrite the path if the location has changed.
            ContextFacade.SetStatusCode((int)context.StatusCode);
            if ((context.Location != originalUrl) && ((int)context.StatusCode < 400))
            {
                if ((int)context.StatusCode < 300)
                {
                    // Successful status if less than 300
                    _configuration.Logger.Info(
                        MessageProvider.FormatString(Message.RewritingXtoY, ContextFacade.GetRawUrl(), context.Location));

                    // Verify that the url exists on this server.
                    HandleDefaultDocument(context); // VerifyResultExists(context);

                    if (context.Location.Contains(@"&"))
                    {
                        var queryStringCollection = HttpUtility.ParseQueryString(new Uri(this.ContextFacade.GetRequestUrl(), context.Location).Query);

                        StringBuilder builder = new StringBuilder();
                        foreach (var value in queryStringCollection.AllKeys.Distinct())
                        {
                            var argument = queryStringCollection.GetValues(value).FirstOrDefault();
                            if (value == "g")
                            {
                                if (context.Location != argument)
                                {
                                    builder.AppendFormat(
                                        "{0}={1}&",
                                        value,
                                        argument);
                                }
                            }
                            else
                            {
                                builder.AppendFormat(
                                    "{0}={1}&",
                                    value,
                                    argument);
                            }
                        }

                        context.Location = context.Location.Remove(context.Location.IndexOf("?") + 1);
                        context.Location = context.Location + builder;

                        if (context.Location.EndsWith(@"&"))
                        {
                            context.Location = context.Location.Remove(context.Location.Length - 1);
                        }
                    }

                    ContextFacade.RewritePath(context.Location);
                }
                else
                {
                    // Redirection
                    _configuration.Logger.Info(
                        MessageProvider.FormatString(
                            Message.RedirectingXtoY, ContextFacade.GetRawUrl(), context.Location));

                    ContextFacade.SetRedirectLocation(context.Location);
                }
            }
            else if ((int)context.StatusCode >= 400)
            {
                HandleError(context);
            }
            else if (HandleDefaultDocument(context))
            {
                ContextFacade.RewritePath(context.Location);
            }

            // Sets the context items.
            SetContextItems(context);
        }
        /// <summary>
        ///     Performs the rewriting.
        /// </summary>
        public void Rewrite()
        {
            string originalUrl = _httpContext.RawUrl.Replace("+", " ");
            RawUrl = originalUrl;

            _configuration.Logger.Debug(MessageProvider.FormatString(Message.StartedProcessing, originalUrl));

            // Create the context
            var context = new RewriteContext(this, originalUrl, _httpContext, _configurationManager);

            // Process each rule.
            ProcessRules(context);

            // Append any headers defined.
            AppendHeaders(context);

            // Append any cookies defined.
            AppendCookies(context);

            // Rewrite the path if the location has changed.
            _httpContext.SetStatusCode((int) context.StatusCode);
            if ((context.Location != originalUrl) && ((int) context.StatusCode < 400))
            {
                if ((int) context.StatusCode < 300)
                {
                    // Successful status if less than 300
                    _configuration.Logger.Info(MessageProvider.FormatString(Message.RewritingXtoY, _httpContext.RawUrl,
                                                                            context.Location));

                    // To verify that the url exists on this server:
                    //  VerifyResultExists(context);

                    // To ensure that directories are rewritten to their default document:
                    //  HandleDefaultDocument(context);

                    _httpContext.RewritePath(context.Location);
                }
                else
                {
                    // Redirection
                    _configuration.Logger.Info(MessageProvider.FormatString(Message.RedirectingXtoY, _httpContext.RawUrl,
                                                                            context.Location));

                    _httpContext.SetRedirectLocation(context.Location);
                }
            }
            else if ((int) context.StatusCode >= 400)
            {
                HandleError(context);
            }
            // To ensure that directories are rewritten to their default document:
            //  else if (HandleDefaultDocument(context))
            //  {
            //      _contextFacade.RewritePath(context.Location);
            //  }

            // Sets the context items.
            SetContextItems(context);
        }