Example #1
0
        /// <summary>
        /// This method is called during the module's BeginRequest event.
        /// </summary>
        /// <param name="requestedRawUrl">The RawUrl being requested (includes path and querystring).</param>
        /// <param name="app">The HttpApplication instance.</param>
        protected override void Rewrite(string requestedPath, System.Web.HttpApplication app)
        {
            // get the configuration rules
            RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;

            // iterate through each rule...
            for (int i = 0; i < rules.Count; i++)
            {
                // get the pattern to look for, and Resolve the Url (convert ~ into the appropriate directory)
                string lookFor = "^" + RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, rules[i].LookFor) + "$";

                // Create a regex (note that IgnoreCase is set...)
                Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);

                // See if a match is found
                if (re.IsMatch(requestedPath))
                {
                    // match found - do any replacement needed
                    string sendToUrl = RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(requestedPath, rules[i].SendTo));

                    // Rewrite the URL
                    RewriterUtils.RewriteUrl(app.Context, sendToUrl);
                    break;                              // exit the for loop
                }
            }
        }
        /// <summary>
        /// GetHandler is executed by the ASP.NET pipeline after the associated HttpModules have run.  The job of
        /// GetHandler is to return an instance of an HttpHandler that can process the page.
        /// </summary>
        /// <param name="context">The HttpContext for this request.</param>
        /// <param name="requestType">The HTTP data transfer method (<b>GET</b> or <b>POST</b>)</param>
        /// <param name="url">The RawUrl of the requested resource.</param>
        /// <param name="pathTranslated">The physical path to the requested resource.</param>
        /// <returns>An instance that implements IHttpHandler; specifically, an HttpHandler instance returned
        /// by the <b>PageParser</b> class, which is the same class that the default ASP.NET PageHandlerFactory delegates
        /// to.</returns>
        public virtual IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
        {
            // log info to the Trace object...
            // context.Trace.Write("RewriterFactoryHandler", "Entering RewriterFactoryHandler");
            // context.Response.Write("RewriterFactoryHandler" + " / " + "Entering RewriterFactoryHandler");

            string sendToUrl = url;

            string filePath = pathTranslated;

            // get the configuration rules
            RewriterRuleCollection rules = RewriterConfigurationView.Instance.Configuration.Rules;

            // iterate through the rules
            for (int i = 0; i < rules.Count; i++)
            {
                // Get the pattern to look for (and resolve its URL)
                string lookfor = string.Format("^{0}$", RewriterUtils.ResolveUrl(context.Request.ApplicationPath, rules[i].Lookfor));

                // Create a regular expression object that ignores case...
                Regex re = new Regex(lookfor, RegexOptions.IgnoreCase);

                // Check to see if we've found a match
                if (re.IsMatch(url))
                {
                    // do any replacement needed
                    sendToUrl = RewriterUtils.ResolveUrl(context.Request.ApplicationPath, re.Replace(url, rules[i].Sendto));

                    //
                    // ��ǿ��ͨ��CustomServicesֱ�Ӷ�̬����Page����֧��.
                    //
                    if (sendToUrl.ToLower().IndexOf("/services/default.aspx") == -1 &&
                        sendToUrl.ToLower().IndexOf("/services/") == 0)
                    {
                        return(GetHandler(context, requestType, sendToUrl, pathTranslated));
                    }

                    // log info to the Trace object...
                    // context.Trace.Write("RewriterFactoryHandler", "Found match, rewriting to " + sendToUrl);

                    // Rewrite the path, getting the querystring-less url and the physical file path
                    string sendToUrlLessQueryString;

                    RewriterUtils.RewriteUrl(context, sendToUrl, out sendToUrlLessQueryString, out filePath);

                    // return a compiled version of the page
                    // context.Trace.Write("RewriterFactoryHandler", "Exiting RewriterFactoryHandler");	// log info to the Trace object...
                    logger.Trace("sendToUrlLessQueryString:" + sendToUrlLessQueryString + ",filePath:" + filePath);

                    return(PageParser.GetCompiledPageInstance(sendToUrlLessQueryString, filePath, context));
                }
            }

            // if we reached this point, we didn't find a rewrite match
            // context.Trace.Write("RewriterFactoryHandler", "Exiting RewriterFactoryHandler");	// log info to the Trace object...
            return(PageParser.GetCompiledPageInstance(url, filePath, context));
        }
Example #3
0
        protected override void LoadViewState(object savedState)
        {
            object[] myState = (object[])savedState;
            if ((myState[0] != null))
            {
                base.LoadViewState(myState[0]);
            }
            if ((myState[1] != null))
            {
                RewriterConfiguration config = new RewriterConfiguration();

                // Deserialize into RewriterConfiguration
                config = (RewriterConfiguration)XmlUtils.Deserialize(myState[1].ToString(), config.GetType());
                Rules  = config.Rules;
            }
        }
Example #4
0
        /// <summary>
        /// GetHandler is executed by the ASP.NET pipeline after the associated HttpModules have run.  The job of
        /// GetHandler is to return an instance of an HttpHandler that can process the page.
        /// </summary>
        /// <param name="context">The HttpContext for this request.</param>
        /// <param name="requestType">The HTTP data transfer method (<b>GET</b> or <b>POST</b>)</param>
        /// <param name="url">The RawUrl of the requested resource.</param>
        /// <param name="pathTranslated">The physical path to the requested resource.</param>
        /// <returns>An instance that implements IHttpHandler; specifically, an HttpHandler instance returned
        /// by the <b>PageParser</b> class, which is the same class that the default ASP.NET PageHandlerFactory delegates
        /// to.</returns>
        public virtual IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
        {
            // log info to the Trace object...
            context.Trace.Write("RewriterFactoryHandler", "Entering RewriterFactoryHandler");

            string sendToUrl = url;
            string filePath  = pathTranslated;

            // get the configuration rules
            RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;

            // iterate through the rules
            for (int i = 0; i < rules.Count; i++)
            {
                // Get the pattern to look for (and resolve its URL)
                string lookFor = "^" + RewriterUtils.ResolveUrl(context.Request.ApplicationPath, rules[i].LookFor) + "$";

                // Create a regular expression object that ignores case...
                Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);

                // Check to see if we've found a match
                if (re.IsMatch(url))
                {
                    // do any replacement needed
                    sendToUrl = RewriterUtils.ResolveUrl(context.Request.ApplicationPath, re.Replace(url, rules[i].SendTo));

                    // log info to the Trace object...
                    context.Trace.Write("RewriterFactoryHandler", "Found match, rewriting to " + sendToUrl);

                    // Rewrite the path, getting the querystring-less url and the physical file path
                    string sendToUrlLessQString;
                    RewriterUtils.RewriteUrl(context, sendToUrl, out sendToUrlLessQString, out filePath);

                    // return a compiled version of the page
                    context.Trace.Write("RewriterFactoryHandler", "Exiting RewriterFactoryHandler");    // log info to the Trace object...
                    return(PageParser.GetCompiledPageInstance(sendToUrlLessQString, filePath, context));
                }
            }


            // if we reached this point, we didn't find a rewrite match
            context.Trace.Write("RewriterFactoryHandler", "Exiting RewriterFactoryHandler");    // log info to the Trace object...
            return(PageParser.GetCompiledPageInstance(url, filePath, context));
        }
Example #5
0
        protected override void LoadViewState(object savedState)
        {
            var myState = (object[])savedState;

            if ((myState[0] != null))
            {
                base.LoadViewState(myState[0]);
            }
            if ((myState[1] != null))
            {
                var config = new RewriterConfiguration();

                //Deserialize into RewriterConfiguration
                var xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(Convert.ToString(myState[1]));
                config = CBO.DeserializeObject <RewriterConfiguration>(xmlDocument);
                Rules  = config.Rules;
            }
        }
Example #6
0
        protected override void LoadViewState(object savedState)
        {
            var myState = (object[])savedState;

            if ((myState[0] != null))
            {
                base.LoadViewState(myState[0]);
            }
            if ((myState[1] != null))
            {
                var config = new RewriterConfiguration();

                //Deserialize into RewriterConfiguration
#pragma warning disable 612,618
                config = (RewriterConfiguration)XmlUtils.Deserialize(Convert.ToString(myState[1]), config.GetType());
#pragma warning restore 612,618
                Rules = config.Rules;
            }
        }
Example #7
0
        protected override void Rewrite(string requestedPath, System.Web.HttpApplication app)
        {
            try
            {
                RewriterRuleCollection rules = RewriterConfiguration.GetConfig(Helper.GetDomain(app.Request.Url.Authority)).Rules;

                for (int counterRule = 0; counterRule < rules.Count; counterRule++)
                {
                    string lookFor = "^" + RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, rules[counterRule].LookFor) + "$";

                    Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);

                    if (re.IsMatch(requestedPath))
                    {
                        string sendToUrl = RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(requestedPath, rules[counterRule].SendTo));
                        RewriterUtils.RewriteUrl(app.Context, sendToUrl);
                        break;
                    }
                }
            }
            catch { }
        }
Example #8
0
        private void RewriteUrl(HttpApplication app, out string portalAlias)
        {
            HttpRequest  request       = app.Request;
            HttpResponse response      = app.Response;
            string       requestedPath = app.Request.Url.AbsoluteUri;

            portalAlias = string.Empty;

            // determine portal alias looking for longest possible match
            string          myAlias = Globals.GetDomainName(app.Request, true);
            PortalAliasInfo objPortalAlias;

            do
            {
                objPortalAlias = PortalAliasController.Instance.GetPortalAlias(myAlias);

                if (objPortalAlias != null)
                {
                    portalAlias = myAlias;
                    break;
                }

                int slashIndex = myAlias.LastIndexOf('/');
                myAlias = slashIndex > 1 ? myAlias.Substring(0, slashIndex) : string.Empty;
            }while (myAlias.Length > 0);

            app.Context.Items.Add("UrlRewrite:OriginalUrl", app.Request.Url.AbsoluteUri);

            // Friendly URLs are exposed externally using the following format
            // http://www.domain.com/tabid/###/mid/###/ctl/xxx/default.aspx
            // and processed internally using the following format
            // http://www.domain.com/default.aspx?tabid=###&mid=###&ctl=xxx
            // The system for accomplishing this is based on an extensible Regex rules definition stored in /SiteUrls.config
            string sendTo = string.Empty;

            // save and remove the querystring as it gets added back on later
            // path parameter specifications will take precedence over querystring parameters
            string strQueryString = string.Empty;

            if (!string.IsNullOrEmpty(app.Request.Url.Query))
            {
                strQueryString = request.QueryString.ToString();
                requestedPath  = requestedPath.Replace(app.Request.Url.Query, string.Empty);
            }

            // get url rewriting rules
            RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;

            // iterate through list of rules
            int matchIndex = -1;

            for (int ruleIndex = 0; ruleIndex <= rules.Count - 1; ruleIndex++)
            {
                // check for the existence of the LookFor value
                string pattern = "^" +
                                 RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, rules[ruleIndex].LookFor) +
                                 "$";
                Match objMatch = Regex.Match(requestedPath, pattern, RegexOptions.IgnoreCase);

                // if there is a match
                if (objMatch.Success)
                {
                    // create a new URL using the SendTo regex value
                    sendTo = RewriterUtils.ResolveUrl(
                        app.Context.Request.ApplicationPath,
                        Regex.Replace(requestedPath, pattern, rules[ruleIndex].SendTo,
                                      RegexOptions.IgnoreCase));

                    string parameters = objMatch.Groups[2].Value;

                    // process the parameters
                    if (parameters.Trim().Length > 0)
                    {
                        // split the value into an array based on "/" ( ie. /tabid/##/ )
                        parameters = parameters.Replace("\\", "/");
                        string[] splitParameters = parameters.Split('/');

                        // icreate a well formed querystring based on the array of parameters
                        for (int parameterIndex = 0; parameterIndex < splitParameters.Length; parameterIndex++)
                        {
                            // ignore the page name
                            if (
                                splitParameters[parameterIndex].IndexOf(
                                    ".aspx",
                                    StringComparison.InvariantCultureIgnoreCase) ==
                                -1)
                            {
                                // get parameter name
                                string parameterName = splitParameters[parameterIndex].Trim();
                                if (parameterName.Length > 0)
                                {
                                    // add parameter to SendTo if it does not exist already
                                    if (
                                        sendTo.IndexOf(
                                            "?" + parameterName + "=",
                                            StringComparison.InvariantCultureIgnoreCase) == -1 &&
                                        sendTo.IndexOf(
                                            "&" + parameterName + "=",
                                            StringComparison.InvariantCultureIgnoreCase) == -1)
                                    {
                                        // get parameter delimiter
                                        string parameterDelimiter = sendTo.IndexOf("?", StringComparison.Ordinal) != -1 ? "&" : "?";
                                        sendTo = sendTo + parameterDelimiter + parameterName;

                                        // get parameter value
                                        string parameterValue = string.Empty;
                                        if (parameterIndex < splitParameters.Length - 1)
                                        {
                                            parameterIndex += 1;
                                            if (!string.IsNullOrEmpty(splitParameters[parameterIndex].Trim()))
                                            {
                                                parameterValue = splitParameters[parameterIndex].Trim();
                                            }
                                        }

                                        // add the parameter value
                                        if (parameterValue.Length > 0)
                                        {
                                            sendTo = sendTo + "=" + parameterValue;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    matchIndex = ruleIndex;
                    break; // exit as soon as it processes the first match
                }
            }

            if (!string.IsNullOrEmpty(strQueryString))
            {
                // add querystring parameters back to SendTo
                string[] parameters = strQueryString.Split('&');

                // iterate through the array of parameters
                for (int parameterIndex = 0; parameterIndex <= parameters.Length - 1; parameterIndex++)
                {
                    // get parameter name
                    string parameterName = parameters[parameterIndex];
                    if (parameterName.IndexOf("=", StringComparison.Ordinal) != -1)
                    {
                        parameterName = parameterName.Substring(0, parameterName.IndexOf("=", StringComparison.Ordinal));
                    }

                    // check if parameter already exists
                    if (sendTo.IndexOf("?" + parameterName + "=", StringComparison.InvariantCultureIgnoreCase) == -1 &&
                        sendTo.IndexOf("&" + parameterName + "=", StringComparison.InvariantCultureIgnoreCase) == -1)
                    {
                        // add parameter to SendTo value
                        sendTo = sendTo.IndexOf("?", StringComparison.Ordinal) != -1
                                     ? sendTo + "&" + parameters[parameterIndex]
                                     : sendTo + "?" + parameters[parameterIndex];
                    }
                }
            }

            // if a match was found to the urlrewrite rules
            if (matchIndex != -1)
            {
                if (rules[matchIndex].SendTo.StartsWith("~"))
                {
                    // rewrite the URL for internal processing
                    RewriterUtils.RewriteUrl(app.Context, sendTo);
                }
                else
                {
                    // it is not possible to rewrite the domain portion of the URL so redirect to the new URL
                    response.Redirect(sendTo, true);
                }
            }
            else
            {
                // Try to rewrite by TabPath
                string url;
                if (Globals.UsePortNumber() &&
                    ((app.Request.Url.Port != 80 && !app.Request.IsSecureConnection) ||
                     (app.Request.Url.Port != 443 && app.Request.IsSecureConnection)))
                {
                    url = app.Request.Url.Host + ":" + app.Request.Url.Port + app.Request.Url.LocalPath;
                }
                else
                {
                    url = app.Request.Url.Host + app.Request.Url.LocalPath;
                }

                if (!string.IsNullOrEmpty(myAlias))
                {
                    if (objPortalAlias != null)
                    {
                        int portalID = objPortalAlias.PortalID;

                        // Identify Tab Name
                        string tabPath = url;
                        if (tabPath.StartsWith(myAlias))
                        {
                            tabPath = url.Remove(0, myAlias.Length);
                        }

                        // Default Page has been Requested
                        if (tabPath == "/" + Globals.glbDefaultPage.ToLowerInvariant())
                        {
                            return;
                        }

                        // Start of patch
                        string cultureCode = string.Empty;

                        Dictionary <string, Locale> dicLocales = LocaleController.Instance.GetLocales(portalID);
                        if (dicLocales.Count > 1)
                        {
                            string[] splitUrl = app.Request.Url.ToString().Split('/');

                            foreach (string culturePart in splitUrl)
                            {
                                if (culturePart.IndexOf("-", StringComparison.Ordinal) > -1)
                                {
                                    foreach (KeyValuePair <string, Locale> key in dicLocales)
                                    {
                                        if (key.Key.ToLower().Equals(culturePart.ToLower()))
                                        {
                                            cultureCode = key.Value.Code;
                                            tabPath     = tabPath.Replace("/" + culturePart, string.Empty);
                                            break;
                                        }
                                    }
                                }
                            }
                        }

                        // Check to see if the tab exists (if localization is enable, check for the specified culture)
                        int tabID = TabController.GetTabByTabPath(
                            portalID,
                            tabPath.Replace("/", "//").Replace(".aspx", string.Empty),
                            cultureCode);

                        // Check to see if neutral culture tab exists
                        if (tabID == Null.NullInteger && cultureCode.Length > 0)
                        {
                            tabID = TabController.GetTabByTabPath(
                                portalID,
                                tabPath.Replace("/", "//").Replace(".aspx", string.Empty), string.Empty);
                        }

                        // End of patch
                        if (tabID != Null.NullInteger)
                        {
                            string sendToUrl = "~/" + Globals.glbDefaultPage + "?TabID=" + tabID;
                            if (!cultureCode.Equals(string.Empty))
                            {
                                sendToUrl = sendToUrl + "&language=" + cultureCode;
                            }

                            if (!string.IsNullOrEmpty(app.Request.Url.Query))
                            {
                                sendToUrl = sendToUrl + "&" + app.Request.Url.Query.TrimStart('?');
                            }

                            RewriterUtils.RewriteUrl(app.Context, sendToUrl);
                            return;
                        }

                        tabPath = tabPath.ToLowerInvariant();
                        if (tabPath.IndexOf('?') != -1)
                        {
                            tabPath = tabPath.Substring(0, tabPath.IndexOf('?'));
                        }

                        // Get the Portal
                        PortalInfo portal       = PortalController.Instance.GetPortal(portalID);
                        string     requestQuery = app.Request.Url.Query;
                        if (!string.IsNullOrEmpty(requestQuery))
                        {
                            requestQuery = TabIdRegex.Replace(requestQuery, string.Empty);
                            requestQuery = PortalIdRegex.Replace(requestQuery, string.Empty);
                            requestQuery = requestQuery.TrimStart('?', '&');
                        }

                        if (tabPath == "/login.aspx")
                        {
                            if (portal.LoginTabId > Null.NullInteger && Globals.ValidateLoginTabID(portal.LoginTabId))
                            {
                                if (!string.IsNullOrEmpty(requestQuery))
                                {
                                    RewriterUtils.RewriteUrl(
                                        app.Context,
                                        "~/" + Globals.glbDefaultPage + "?TabID=" +
                                        portal.LoginTabId + "&" + requestQuery);
                                }
                                else
                                {
                                    RewriterUtils.RewriteUrl(
                                        app.Context,
                                        "~/" + Globals.glbDefaultPage + "?TabID=" +
                                        portal.LoginTabId);
                                }
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(requestQuery))
                                {
                                    RewriterUtils.RewriteUrl(
                                        app.Context,
                                        "~/" + Globals.glbDefaultPage + "?TabID=" +
                                        portal.HomeTabId + "&portalid=" + portalID + "&ctl=login&" +
                                        requestQuery);
                                }
                                else
                                {
                                    RewriterUtils.RewriteUrl(
                                        app.Context,
                                        "~/" + Globals.glbDefaultPage + "?TabID=" +
                                        portal.HomeTabId + "&portalid=" + portalID + "&ctl=login");
                                }
                            }

                            return;
                        }

                        if (tabPath == "/register.aspx")
                        {
                            if (portal.RegisterTabId > Null.NullInteger)
                            {
                                if (!string.IsNullOrEmpty(requestQuery))
                                {
                                    RewriterUtils.RewriteUrl(
                                        app.Context,
                                        "~/" + Globals.glbDefaultPage + "?TabID=" +
                                        portal.RegisterTabId + "&portalid=" + portalID + "&" +
                                        requestQuery);
                                }
                                else
                                {
                                    RewriterUtils.RewriteUrl(
                                        app.Context,
                                        "~/" + Globals.glbDefaultPage + "?TabID=" +
                                        portal.RegisterTabId + "&portalid=" + portalID);
                                }
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(requestQuery))
                                {
                                    RewriterUtils.RewriteUrl(
                                        app.Context,
                                        "~/" + Globals.glbDefaultPage + "?TabID=" +
                                        portal.HomeTabId + "&portalid=" + portalID +
                                        "&ctl=Register&" + requestQuery);
                                }
                                else
                                {
                                    RewriterUtils.RewriteUrl(
                                        app.Context,
                                        "~/" + Globals.glbDefaultPage + "?TabID=" +
                                        portal.HomeTabId + "&portalid=" + portalID +
                                        "&ctl=Register");
                                }
                            }

                            return;
                        }

                        if (tabPath == "/terms.aspx")
                        {
                            if (!string.IsNullOrEmpty(requestQuery))
                            {
                                RewriterUtils.RewriteUrl(
                                    app.Context,
                                    "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId +
                                    "&portalid=" + portalID + "&ctl=Terms&" + requestQuery);
                            }
                            else
                            {
                                RewriterUtils.RewriteUrl(
                                    app.Context,
                                    "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId +
                                    "&portalid=" + portalID + "&ctl=Terms");
                            }

                            return;
                        }

                        if (tabPath == "/privacy.aspx")
                        {
                            if (!string.IsNullOrEmpty(requestQuery))
                            {
                                RewriterUtils.RewriteUrl(
                                    app.Context,
                                    "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId +
                                    "&portalid=" + portalID + "&ctl=Privacy&" + requestQuery);
                            }
                            else
                            {
                                RewriterUtils.RewriteUrl(
                                    app.Context,
                                    "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId +
                                    "&portalid=" + portalID + "&ctl=Privacy");
                            }

                            return;
                        }

                        tabPath = tabPath.Replace("/", "//");
                        tabPath = tabPath.Replace(".aspx", string.Empty);
                        TabCollection objTabs = TabController.Instance.GetTabsByPortal(tabPath.StartsWith("//host") ? Null.NullInteger : portalID);
                        foreach (KeyValuePair <int, TabInfo> kvp in objTabs)
                        {
                            if (kvp.Value.IsDeleted == false && kvp.Value.TabPath.ToLowerInvariant() == tabPath)
                            {
                                if (!string.IsNullOrEmpty(app.Request.Url.Query))
                                {
                                    RewriterUtils.RewriteUrl(
                                        app.Context,
                                        "~/" + Globals.glbDefaultPage + "?TabID=" + kvp.Value.TabID +
                                        "&" + app.Request.Url.Query.TrimStart('?'));
                                }
                                else
                                {
                                    RewriterUtils.RewriteUrl(
                                        app.Context,
                                        "~/" + Globals.glbDefaultPage + "?TabID=" + kvp.Value.TabID);
                                }

                                return;
                            }
                        }
                    }
                }
            }
        }
Example #9
0
        public void OnBeginRequest(object s, EventArgs e)
        {
            HttpApplication   app           = (HttpApplication)s;
            HttpServerUtility Server        = app.Server;
            HttpRequest       Request       = app.Request;
            HttpResponse      Response      = app.Response;
            string            requestedPath = app.Request.Url.AbsoluteUri;

            // URL validation
            // check for ".." escape characters commonly used by hackers to traverse the folder tree on the server
            // the application should always use the exact relative location of the resource it is requesting
            string strURL             = Request.Url.AbsolutePath;
            string strDoubleDecodeURL = Server.UrlDecode(Server.UrlDecode(Request.RawUrl));

            if (strURL.IndexOf("..") != -1 || strDoubleDecodeURL.IndexOf("..") != -1)
            {
                throw (new HttpException(404, "Not Found"));
            }

            //fix for ASP.NET canonicalization issues http://support.microsoft.com/?kbid=887459
            if (Request.Path.IndexOf('\u005C') >= 0 || Path.GetFullPath(Request.PhysicalPath) != Request.PhysicalPath)
            {
                throw (new HttpException(404, "Not Found"));
            }

            //check if we are upgrading/installing
            if (Request.Url.LocalPath.ToLower().EndsWith("install.aspx"))
            {
                return;
            }

            // save original url in context
            app.Context.Items.Add("UrlRewrite:OriginalUrl", app.Request.Url.AbsoluteUri);

            // Friendly URLs are exposed externally using the following format
            // http://www.domain.com/tabid/###/mid/###/ctl/xxx/default.aspx
            // and processed internally using the following format
            // http://www.domain.com/default.aspx?tabid=###&mid=###&ctl=xxx
            // The system for accomplishing this is based on an extensible Regex rules definition stored in /SiteUrls.config
            string sendTo = "";

            // save and remove the querystring as it gets added back on later
            // path parameter specifications will take precedence over querystring parameters
            string strQueryString = "";

            if (!String.IsNullOrEmpty(app.Request.Url.Query))
            {
                strQueryString = Request.QueryString.ToString();
                requestedPath  = requestedPath.Replace(app.Request.Url.Query, "");
            }

            // get url rewriting rules
            RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;

            // iterate through list of rules
            int intMatch = -1;

            for (int intRule = 0; intRule <= rules.Count - 1; intRule++)
            {
                // check for the existence of the LookFor value
                string strLookFor = "^" + RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, rules[intRule].LookFor) + "$";
                Regex  objLookFor = new Regex(strLookFor, RegexOptions.IgnoreCase);
                // if there is a match
                if (objLookFor.IsMatch(requestedPath))
                {
                    // create a new URL using the SendTo regex value
                    sendTo = RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, objLookFor.Replace(requestedPath, rules[intRule].SendTo));
                    // obtain the RegEx match group which contains the parameters
                    Match  objMatch      = objLookFor.Match(requestedPath);
                    string strParameters = objMatch.Groups[2].Value;
                    // process the parameters
                    if (strParameters.Trim(null).Length > 0)
                    {
                        // split the value into an array based on "/" ( ie. /tabid/##/ )
                        strParameters = strParameters.Replace("\\", "/");
                        string[] arrParameters = strParameters.Split('/');
                        string   strParameterDelimiter;
                        string   strParameterName;
                        string   strParameterValue;
                        // icreate a well formed querystring based on the array of parameters
                        for (int intParameter = 1; intParameter <= arrParameters.Length - 1; intParameter++)
                        {
                            // ignore the page name
                            if (arrParameters[intParameter].ToLower().IndexOf(".aspx") == -1)
                            {
                                // get parameter name
                                strParameterName = arrParameters[intParameter].Trim(null);
                                if (strParameterName.Length > 0)
                                {
                                    // add parameter to SendTo if it does not exist already
                                    if (sendTo.ToLower().IndexOf("?" + strParameterName.ToLower()) == -1 && sendTo.ToLower().IndexOf("&" + strParameterName.ToLower()) == -1)
                                    {
                                        // get parameter delimiter
                                        if (sendTo.IndexOf("?") != -1)
                                        {
                                            strParameterDelimiter = "&";
                                        }
                                        else
                                        {
                                            strParameterDelimiter = "?";
                                        }
                                        sendTo = sendTo + strParameterDelimiter + strParameterName;
                                        // get parameter value
                                        strParameterValue = "";
                                        if (intParameter < (arrParameters.Length - 1))
                                        {
                                            intParameter++;
                                            if (arrParameters[intParameter].Trim() != "")
                                            {
                                                strParameterValue = arrParameters[intParameter].Trim(null);
                                            }
                                        }
                                        // add the parameter value
                                        if (strParameterValue.Length > 0)
                                        {
                                            sendTo = sendTo + "=" + strParameterValue;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    intMatch = intRule;
                    break; // exit as soon as it processes the first match
                }
            }

            // add querystring parameters back to SendTo
            if (!String.IsNullOrEmpty(strQueryString))
            {
                string[] arrParameters = strQueryString.Split('&');
                // iterate through the array of parameters
                for (int intParameter = 0; intParameter <= arrParameters.Length - 1; intParameter++)
                {
                    // get parameter name
                    string strParameterName = arrParameters[intParameter];
                    if (strParameterName.IndexOf("=") != -1)
                    {
                        strParameterName = strParameterName.Substring(0, strParameterName.IndexOf("="));
                    }
                    // check if parameter already exists
                    if (sendTo.ToLower().IndexOf("?" + strParameterName.ToLower()) == -1 && sendTo.ToLower().IndexOf("&" + strParameterName.ToLower()) == -1)
                    {
                        // add parameter to SendTo value
                        if (sendTo.IndexOf("?") != -1)
                        {
                            sendTo = sendTo + "&" + arrParameters[intParameter];
                        }
                        else
                        {
                            sendTo = sendTo + "?" + arrParameters[intParameter];
                        }
                    }
                }
            }

            // if a match was found to the urlrewrite rules
            if (intMatch != -1)
            {
                if (rules[intMatch].SendTo.StartsWith("~"))
                {
                    // rewrite the URL for internal processing
                    RewriterUtils.RewriteUrl(app.Context, sendTo);
                }
                else
                {
                    // it is not possible to rewrite the domain portion of the URL so redirect to the new URL
                    Response.Redirect(sendTo, true);
                }
            }

            // *Note: from this point on we are dealing with a "standard" querystring ( ie. http://www.domain.com/default.aspx?tabid=## )

            int             TabId       = -1;
            int             PortalId    = -1;
            string          DomainName  = null;
            string          PortalAlias = null;
            PortalAliasInfo objPortalAliasInfo;

            // get TabId from querystring ( this is mandatory for maintaining portal context for child portals )
            try
            {
                if (!(Request.QueryString["tabid"] == null))
                {
                    TabId = int.Parse(Request.QueryString["tabid"]);
                }
                // get PortalId from querystring ( this is used for host menu options as well as child portal navigation )
                if (!(Request.QueryString["portalid"] == null))
                {
                    PortalId = int.Parse(Request.QueryString["portalid"]);
                }
            }
            catch (Exception)
            {
                //The tabId or PortalId are incorrectly formatted (potential DOS)
                throw (new HttpException(404, "Not Found"));
            }

            // alias parameter can be used to switch portals
            if (!(Request.QueryString["alias"] == null))
            {
                // check if the alias is valid
                if (PortalSettings.GetPortalAliasInfo(Request.QueryString["alias"]) != null)
                {
                    // check if the domain name contains the alias
                    if (Strings.InStr(1, Request.QueryString["alias"], DomainName, CompareMethod.Text) == 0)
                    {
                        // redirect to the url defined in the alias
                        Response.Redirect(Globals.GetPortalDomainName(Request.QueryString["alias"], Request, true));
                    }
                    else // the alias is the same as the current domain
                    {
                        PortalAlias = Request.QueryString["alias"];
                    }
                }
            }

            // parse the Request URL into a Domain Name token
            DomainName = Globals.GetDomainName(Request);

            // PortalId identifies a portal when set
            if (PortalAlias == null)
            {
                if (PortalId != -1)
                {
                    PortalAlias = PortalSettings.GetPortalByID(PortalId, DomainName);
                }
            }

            // TabId uniquely identifies a Portal
            if (PortalAlias == null)
            {
                if (TabId != -1)
                {
                    // get the alias from the tabid, but only if it is for a tab in that domain
                    PortalAlias = PortalSettings.GetPortalByTab(TabId, DomainName);
                    if (PortalAlias == null || PortalAlias == "")
                    {
                        //if the TabId is not for the correct domain
                        //see if the correct domain can be found and redirect it
                        objPortalAliasInfo = PortalSettings.GetPortalAliasInfo(DomainName);
                        if (objPortalAliasInfo != null)
                        {
                            if (app.Request.Url.AbsoluteUri.ToLower().StartsWith("https://"))
                            {
                                strURL = "https://" + objPortalAliasInfo.HTTPAlias.Replace("*.", "");
                            }
                            else
                            {
                                strURL = "http://" + objPortalAliasInfo.HTTPAlias.Replace("*.", "");
                            }
                            if (strURL.ToLower().IndexOf(DomainName.ToLower()) == -1)
                            {
                                strURL += app.Request.Url.PathAndQuery;
                            }
                            Response.Redirect(strURL, true);
                        }
                    }
                }
            }

            // else use the domain name
            if (PortalAlias == null || PortalAlias == "")
            {
                PortalAlias = DomainName;
            }
            //using the DomainName above will find that alias that is the domainname portion of the Url
            //ie. dotnetnuke.com will be found even if zzz.dotnetnuke.com was entered on the Url
            objPortalAliasInfo = PortalSettings.GetPortalAliasInfo(PortalAlias);
            if (objPortalAliasInfo != null)
            {
                PortalId = objPortalAliasInfo.PortalID;
            }

            // if the portalid is not known
            if (PortalId == -1)
            {
                if (!Request.Url.LocalPath.ToLower().EndsWith(Globals.glbDefaultPage.ToLower()))
                {
                    // allows requests for aspx pages in custom folder locations to be processed
                    return;
                }
                else
                {
                    //the domain name was not found so try using the host portal's first alias
                    if (Convert.ToString(Globals.HostSettings["HostPortalId"]) != "")
                    {
                        PortalId = Convert.ToInt32(Globals.HostSettings["HostPortalId"]);
                        // use the host portal
                        PortalAliasController objPortalAliasController = new PortalAliasController();
                        ArrayList             arrPortalAliases;
                        arrPortalAliases = objPortalAliasController.GetPortalAliasArrayByPortalID(int.Parse(Convert.ToString(Globals.HostSettings["HostPortalId"])));
                        if (arrPortalAliases.Count > 0)
                        {
                            //Get the first Alias
                            objPortalAliasInfo = (PortalAliasInfo)arrPortalAliases[0];
                            if (app.Request.Url.AbsoluteUri.ToLower().StartsWith("https://"))
                            {
                                strURL = "https://" + objPortalAliasInfo.HTTPAlias.Replace("*.", "");
                            }
                            else
                            {
                                strURL = "http://" + objPortalAliasInfo.HTTPAlias.Replace("*.", "");
                            }
                            if (TabId != -1)
                            {
                                strURL += app.Request.Url.Query;
                            }
                            Response.Redirect(strURL, true);
                        }
                    }
                }
            }

            if (PortalId != -1)
            {
                // load the PortalSettings into current context
                PortalSettings _portalSettings = new PortalSettings(TabId, objPortalAliasInfo);
                app.Context.Items.Add("PortalSettings", _portalSettings);
            }
            else
            {
                // alias does not exist in database
                // and all attempts to find another have failed
                //this should only happen if the HostPortal does not have any aliases
                StreamReader objStreamReader;
                objStreamReader = File.OpenText(Server.MapPath("~/404.htm"));
                string strHTML = objStreamReader.ReadToEnd();
                objStreamReader.Close();
                strHTML = strHTML.Replace("[DOMAINNAME]", DomainName);
                Response.Write(strHTML);
                Response.End();
            }
        }