RewritePath() public method

public RewritePath ( string path ) : void
path string
return void
Beispiel #1
0
        /// <summary>
        /// Handles the current request.
        /// </summary>
        /// <param name="context">The current context</param>
        /// <param name="draft">Weather to view the draft</param>
        /// <param name="args">Optional url arguments passed to the handler</param>
        protected virtual void HandleRequest(HttpContext context, bool draft, params string[] args)
        {
            if (args != null && args.Length > 0) {
                Permalink perm = Permalink.GetByName(args[0]) ;

                if (perm != null) {
                    if (perm.Type == Permalink.PermalinkType.PAGE) {
                        Page page = Page.GetSingle(perm.ParentId, draft) ;

                        if (!String.IsNullOrEmpty(page.Controller)) {
                            context.RewritePath("~/templates/" + page.Controller + "/" + perm.Name +
                                (draft ? "?draft=true" : ""), false) ;
                        } else {
                            context.RewritePath("~/page/" + perm.Name + (draft ? "?draft=true" : "")) ;
                        }
                    } else {
                        context.RewritePath("~/post/" + perm.Name + (draft ? "?draft=true" : "")) ;
                    }
                }
            } else {
                //
                // Rewrite to current startpage
                //
                Page page = Page.GetStartpage() ;

                if (!String.IsNullOrEmpty(page.Controller))
                    context.RewritePath("~/templates/" + page.Controller, false) ;
                else context.RewritePath("~/page") ;
            }
        }
Beispiel #2
0
		/// <summary>
		/// Handles requests to the current startpage
		/// </summary>
		/// <param name="context">The current http context</param>
		public void HandleStartpage(HttpContext context) {
			var page = Page.GetStartpage();

			if (!String.IsNullOrEmpty(page.Controller))
				context.RewritePath("~/" + page.Controller + "?permalink=" + page.Permalink + FormatQuerystring(context), false);
			else context.RewritePath("~/page?permalink=" + page.Permalink + FormatQuerystring(context), false);
		}
Beispiel #3
0
		/// <summary>
		/// Handles requests to the given page.
		/// </summary>
		/// <param name="context">The current http context</param>
		/// <param name="permalink">The permalink</param>
		/// <param name="page">The page</param>
		/// <param name="args">Optional route arguments</param>
		public void HandlePage(HttpContext context, Permalink permalink, Page page, params string[] args) {
			if (!String.IsNullOrEmpty(page.Controller)) {
				context.RewritePath("~/" + page.Controller + "/" + args.Implode("/") + "?permalink=" + permalink.Name +
					(page.IsDraft ? "&draft=true" : "") + FormatQuerystring(context), false);
			} else {
				context.RewritePath("~/page/" + args.Implode("/") + "?permalink=" + permalink.Name +
					(page.IsDraft ? "&draft=true" : "") + FormatQuerystring(context), false);
			}
		}
        IHttpHandler IHttpHandlerFactory.GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
        {
            IHttpHandler handler = null;

            if (context.Request.QueryString != null)
                pathTranslated = getPathTranslatedFromSiteGeneratorGUI(url, pathTranslated);
            // check if it is an .aspx page
            if (".aspx" == Path.GetExtension(pathTranslated))
            {
                context.RewritePath(url, url, context.Request.QueryString.ToString());
                handler = PageParser.GetCompiledPageInstance(url, pathTranslated, context);
            }
            else if (".asmx" == Path.GetExtension(pathTranslated).ToLower())
            {
                WebServiceHandlerFactory wshf = new WebServiceHandlerFactory();
                handler = wshf.GetHandler(context, requestType, url, pathTranslated);
            }
            else
            {
                ProcessStaticContent(pathTranslated);      // Process page and
                HttpContext.Current.Response.End();     //  end here
            }

            return handler;
        }
        /// <summary>
        /// Rewrites the post.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="url">The URL string.</param>
        public static void RewritePost(HttpContext context, string url)
        {
            int year, month, day;

            var haveDate = ExtractDate(context, out year, out month, out day);
            var slug = ExtractTitle(context, url);

            // Allow for Year/Month only dates in URL (in this case, day == 0), as well as Year/Month/Day dates.
            // first make sure the Year and Month match.
            // if a day is also available, make sure the Day matches.
            var post = Post.ApplicablePosts.Find(
                p =>
                (!haveDate || (p.DateCreated.Year == year && p.DateCreated.Month == month)) &&
                ((!haveDate || (day == 0 || p.DateCreated.Day == day)) &&
                 slug.Equals(Utils.RemoveIllegalCharacters(p.Slug), StringComparison.OrdinalIgnoreCase)));

            if (post == null)
            {
                return;
            }

            var q = GetQueryString(context);
            if (q.Contains("id=" + post.Id, StringComparison.OrdinalIgnoreCase))
                q = string.Format("{0}post.aspx?{1}", Utils.ApplicationRelativeWebRoot, q);
            else
                q = string.Format("{0}post.aspx?id={1}{2}", Utils.ApplicationRelativeWebRoot, post.Id, q);

            context.RewritePath(
                url.Contains("/FEED/")
                    ? string.Format("syndication.axd?post={0}{1}", post.Id, GetQueryString(context))
                    : q,
                false);
        }
Beispiel #6
0
 public void ProcessRequest(HttpContext context)
 {
     HttpRequest req=context.Request;
     HttpResponse res=context.Response;
     string path = req.Path;
     if(Path.GetExtension(path)==".aspx") context.RewritePath(path.Replace("/RAGS/","/"));
 }
Beispiel #7
0
        /// <summary>
        /// Rewrite's a URL using <b>HttpContext.RewriteUrl()</b>.
        /// </summary>
        /// <param name="context">The HttpContext object to rewrite the URL to.</param>
        /// <param name="sendToUrl">The URL to rewrite to.</param>
        /// <param name="sendToUrlLessQString">Returns the value of sendToUrl stripped of the querystring.</param>
        /// <param name="filePath">Returns the physical file path to the requested page.</param>
        internal static void RewriteUrl(HttpContext context, string sendToUrl, out string sendToUrlLessQString, out string filePath)
        {
            // see if we need to add any extra querystring information
            if (context.Request.QueryString.Count > 0)
            {
                if (sendToUrl.IndexOf('?') != -1)
                    sendToUrl += "&" + context.Request.QueryString.ToString();
                else
                    sendToUrl += "?" + context.Request.QueryString.ToString();
            }

            // first strip the querystring, if any
            string queryString = String.Empty;
            sendToUrlLessQString = sendToUrl;
            if (sendToUrl.IndexOf('?') > 0)
            {
                sendToUrlLessQString = sendToUrl.Substring(0, sendToUrl.IndexOf('?'));
                queryString = sendToUrl.Substring(sendToUrl.IndexOf('?') + 1);
            }

            // grab the file's physical path
            filePath = string.Empty;
            filePath = context.Server.MapPath(sendToUrlLessQString);

            // rewrite the path...
            context.RewritePath(sendToUrlLessQString, String.Empty, queryString);

            // NOTE!  The above RewritePath() overload is only supported in the .NET Framework 1.1
            // If you are using .NET Framework 1.0, use the below form instead:
            // context.RewritePath(sendToUrl);
        }
Beispiel #8
0
        private static void HandleAjax(HttpContext context)
        {
            int dotasmx = context.Request.Path.IndexOf(".asmx");
            string path = context.Request.Path.Substring(0, dotasmx + 5);

            string pathInfo = context.Request.Path.Substring(dotasmx + 5);

            context.RewritePath(path, pathInfo, context.Request.Url.Query);
        }
        public void CondRewrite(HttpContext ctx)
        {
            if ( RewriteNeeded ) {
                Common.Log("ModCaseInsensitive: rewritting [ '{0}' -> '{1}' ]",
                    ctx.Request.RawUrl,
                    Url + PathInfo + QueryString
                );

                if ( PathInfo == String.Empty ) {
                    ctx.RewritePath( Url + QueryString );
                }
                else {
                    ctx.RewritePath( Url, PathInfo, QueryString );
                }
            }
            else {
                Common.Log("ModCaseInsensitive: not rewritting [ '{0}' ]", ctx.Request.RawUrl);
            }
        }
        public override void SendImageToHttpResponse(HttpContext context, string cacheKey, string fileExtension)
        {
            // Instead of sending image directly to the response, just call RewritePath and let IIS
            // handle the actual serving of the image.
            string filePath = GetDiskCacheFilePath(context, cacheKey, fileExtension);

            context.Items["FinalCachedFile"] = context.Server.MapPath(filePath);

            context.RewritePath(filePath, false);
        }
Beispiel #11
0
        /// <summary>
        /// Rewrites the specified HTTP context.
        /// </summary>
        /// <param name="httpContext">The HTTP context.</param>
        public void Rewrite(HttpContext httpContext)
        {
            if (httpContext != null)
            {
                string outputUri = null;

                if (RewriteToUri(httpContext.Request.RawUrl, out outputUri))
                {
                    httpContext.RewritePath(outputUri);
                }
            }
        }
Beispiel #12
0
 private static void RewriteCategory(HttpContext context)
 {
     string title = ExtractTitle(context);
       foreach (Category cat in Category.Categories)
       {
     string legalTitle = SupportUtilities.RemoveIllegalCharacters(cat.Title).ToLowerInvariant();
     if (title.Equals(legalTitle, StringComparison.OrdinalIgnoreCase))
     {
       context.RewritePath(SupportUtilities.RelativeWebRoot + "Default.aspx?id=" + cat.Id.ToString() + GetQueryString(context), false);
       break;
     }
       }
 }
Beispiel #13
0
        internal static void RewriteUrl(HttpContext context, string sendToUrl)
        {
            //first strip the querystring, if any
            var queryString = string.Empty;
            string sendToUrlLessQString = sendToUrl;
            if ((sendToUrl.IndexOf("?", StringComparison.Ordinal) > 0))
            {
                sendToUrlLessQString = sendToUrl.Substring(0, sendToUrl.IndexOf("?", StringComparison.Ordinal));
                queryString = sendToUrl.Substring(sendToUrl.IndexOf("?", StringComparison.Ordinal) + 1);
            }
			
            //rewrite the path..
            context.RewritePath(sendToUrlLessQString, string.Empty, queryString);
            //NOTE!  The above RewritePath() overload is only supported in the .NET Framework 1.1
            //If you are using .NET Framework 1.0, use the below form instead:
            //context.RewritePath(sendToUrl);
        }
Beispiel #14
0
        /// <summary>
        /// Rewrite's a URL using <b>HttpContext.RewriteUrl()</b>.
        /// </summary>
        /// <param name="context">The HttpContext object to rewrite the URL to.</param>
        /// <param name="sendToUrl">The URL to rewrite to.</param>
        /// <param name="sendToUrlLessQString">Returns the value of sendToUrl stripped of the querystring.</param>
        /// <param name="filePath">Returns the physical file path to the requested page.</param>
        internal static void RewriteUrl(HttpContext context, string sendToUrl, out string sendToUrlLessQString, out string filePath)
        {
            if (context.Request.QueryString.Count > 0)
                if (sendToUrl.IndexOf('?') != -1)
                    sendToUrl += "&" + context.Request.QueryString.ToString();
                else
                    sendToUrl += "?" + context.Request.QueryString.ToString();

            string queryString = String.Empty;
            sendToUrlLessQString = sendToUrl;
            if (sendToUrl.IndexOf('?') > 0) {
                sendToUrlLessQString = sendToUrl.Substring(0, sendToUrl.IndexOf('?'));
                queryString = sendToUrl.Substring(sendToUrl.IndexOf('?') + 1);
            }

            filePath = context.Server.MapPath(sendToUrlLessQString);
            context.RewritePath(sendToUrlLessQString, String.Empty, queryString);
        }
        internal static void UrlMappingRewritePath(HttpContext context) {
            HttpRequest request = context.Request;
            UrlMappingsSection urlMappings = RuntimeConfig.GetAppConfig().UrlMappings;
            string path = request.Path;
            string mappedUrl = null;

            // First check path with query string (for legacy reasons)
            string qs = request.QueryStringText;
            if (!String.IsNullOrEmpty(qs)) {
                mappedUrl = urlMappings.HttpResolveMapping(path + "?" + qs);
            }

            // Check Path if not found
            if (mappedUrl == null)
                mappedUrl = urlMappings.HttpResolveMapping(path);

            if (!String.IsNullOrEmpty(mappedUrl))
                context.RewritePath(mappedUrl, false);
        }
 internal static void UrlMappingRewritePath(HttpContext context)
 {
     HttpRequest request = context.Request;
     UrlMappingsSection urlMappings = RuntimeConfig.GetAppConfig().UrlMappings;
     string path = request.Path;
     string str2 = null;
     string queryStringText = request.QueryStringText;
     if (!string.IsNullOrEmpty(queryStringText))
     {
         str2 = urlMappings.HttpResolveMapping(path + "?" + queryStringText);
     }
     if (str2 == null)
     {
         str2 = urlMappings.HttpResolveMapping(path);
     }
     if (!string.IsNullOrEmpty(str2))
     {
         context.RewritePath(str2, false);
     }
 }
Beispiel #17
0
        internal static void UrlMappingRewritePath(HttpContext context)
        {
            HttpRequest        request         = context.Request;
            UrlMappingsSection urlMappings     = RuntimeConfig.GetAppConfig().UrlMappings;
            string             path            = request.Path;
            string             str2            = null;
            string             queryStringText = request.QueryStringText;

            if (!string.IsNullOrEmpty(queryStringText))
            {
                str2 = urlMappings.HttpResolveMapping(path + "?" + queryStringText);
            }
            if (str2 == null)
            {
                str2 = urlMappings.HttpResolveMapping(path);
            }
            if (!string.IsNullOrEmpty(str2))
            {
                context.RewritePath(str2, false);
            }
        }
Beispiel #18
0
        internal static void RewriteUrl(HttpContext context, string sendToUrl, ref string sendToUrlLessQString, ref string filePath)
        {
            //first strip the querystring, if any
            var queryString = string.Empty;
            sendToUrlLessQString = sendToUrl;
            if ((sendToUrl.IndexOf("?") > 0))
            {
                sendToUrlLessQString = sendToUrl.Substring(0, sendToUrl.IndexOf("?"));
                queryString = sendToUrl.Substring(sendToUrl.IndexOf("?") + 1);
            }
			
            //grab the file's physical path
            filePath = string.Empty;
            filePath = context.Server.MapPath(sendToUrlLessQString);

            //rewrite the path..
            context.RewritePath(sendToUrlLessQString, string.Empty, queryString);
            //NOTE!  The above RewritePath() overload is only supported in the .NET Framework 1.1
            //If you are using .NET Framework 1.0, use the below form instead:
            //context.RewritePath(sendToUrl);
        }
Beispiel #19
0
        public static void RewriteUrl(HttpContext context, string sendToUrl, out string sendToUrlLessQString, out string filePath)
        {
            if (context.Request.QueryString.Count > 0)
            {
                if (sendToUrl.IndexOf('?') != -1)
                {
                    sendToUrl = sendToUrl + "&" + context.Request.QueryString.ToString();
                }
                else
                {
                    sendToUrl = sendToUrl + "?" + context.Request.QueryString.ToString();
                }
            }
            string queryString = string.Empty;

            sendToUrlLessQString = sendToUrl;
            if (sendToUrl.IndexOf('?') > 0)
            {
                sendToUrlLessQString = sendToUrl.Substring(0, sendToUrl.IndexOf('?'));
                queryString          = sendToUrl.Substring(sendToUrl.IndexOf('?') + 1);
            }
            filePath = context.Server.MapPath(sendToUrlLessQString);
            context.RewritePath(sendToUrlLessQString, string.Empty, queryString);
        }
Beispiel #20
0
        /// <summary>
        /// Rewrites /blog.aspx path
        /// </summary>
        /// <param name="context">The HTTP context.</param>
        /// <param name="url">The URL string.</param>
        public static void RewriteBlog(HttpContext context, string url)
        {
            var path = string.Format("{0}default.aspx?blog=true{1}",
                Utils.ApplicationRelativeWebRoot,
                GetQueryString(context));

            context.RewritePath(path, false);
        }
Beispiel #21
0
        /// <summary>
        /// Posts for author
        /// </summary>
        /// <param name="context">The HTTP context.</param>
        /// <param name="url">The URL string.</param>
        public static void RewriteAuthor(HttpContext context, string url)
        {
            var author = UrlRules.ExtractTitle(context, url);

            var path = string.Format("{0}default.aspx?name={1}{2}",
                Utils.ApplicationRelativeWebRoot,
                author,
                GetQueryString(context));

            context.RewritePath(path, false);
        }
Beispiel #22
0
        /// <summary>
        /// Page with large calendar
        /// </summary>
        /// <param name="context">The HTTP context.</param>
        /// <param name="url">The URL string.</param>
        public static void RewriteCalendar(HttpContext context, string url)
        {
            // prevent fake URLs
            // valid:   "/calendar/"
            // valid:   "/calendar/default.aspx"
            // invalid: "/fake-value/calendar/default.aspx"
            // invalid: "/calendar/fake-value/default.aspx"

            url = url.ToLower();
            var validUrl = Utils.RelativeWebRoot.ToLower() + "calendar";
            
            if (!url.StartsWith(validUrl))
                throw new HttpException(404, "File not found");
            
            if(url.Contains("default.aspx") && !url.Contains("calendar/default.aspx"))
                throw new HttpException(404, "File not found");

            context.RewritePath(string.Format("{0}default.aspx?calendar=show", Utils.ApplicationRelativeWebRoot), false);
        }
Beispiel #23
0
        /// <summary>
        /// Rewrites the tag.
        /// </summary>
        /// <param name="context">The HTTP context.</param>
        /// <param name="url">The URL string.</param>
        public static void RewriteTag(HttpContext context, string url)
        {
            var tag = ExtractTitle(context, url);

            if (url.Contains("/FEED/"))
            {
                tag = string.Format("syndication.axd?tag={0}{1}", tag, GetQueryString(context));
            }
            else
            {
                tag = string.Format("{0}default.aspx?tag=/{1}{2}", Utils.ApplicationRelativeWebRoot, tag, GetQueryString(context));
            }
            context.RewritePath(tag, false);
        }
Beispiel #24
0
 /// <summary>
 /// Rewrites the category.
 /// </summary>
 /// <param name="context">The HTTP context.</param>
 /// <param name="url">The URL string.</param>
 public static void RewriteCategory(HttpContext context, string url)
 {
     var title = ExtractTitle(context, url);
     foreach (var cat in from cat in Category.ApplicableCategories
                         let legalTitle = Utils.RemoveIllegalCharacters(cat.Title).ToLowerInvariant()
                         where title.Equals(legalTitle, StringComparison.OrdinalIgnoreCase)
                         select cat)
     {
         if (url.Contains("/FEED/"))
         {
             context.RewritePath(string.Format("syndication.axd?category={0}{1}", cat.Id, GetQueryString(context)), false);
         }
         else
         {
             context.RewritePath(
                 string.Format("{0}default.aspx?id={1}{2}", Utils.ApplicationRelativeWebRoot, cat.Id, GetQueryString(context)), false);
             break;
         }
     }
 }
Beispiel #25
0
 /// <summary>
 /// Generic routing to rewrite to a physical page, e.g. contact.aspx, archive.aspx, when RemoveExtensionsFromUrls is turned on.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="url">The URL string.</param>
 /// <param name="relativePath">The relative path to the page including the physical page name, e.g. archive.aspx, folder/somepage.aspx</param>
 private static void RewritePhysicalPageGeneric(HttpContext context, string url, string relativePath)
 {
     string query = GetQueryString(context);
     if (query.Length > 0 && query.StartsWith("&"))
     {
         query = "?" + query.Substring(1);
     }
     context.RewritePath(string.Format("{0}{1}{2}", Utils.ApplicationRelativeWebRoot, relativePath, query), false);
 }
        internal static void RewriteUrl(HttpContext context, string sendToUrl, ref string sendToUrlLessQString, ref string filePath)
        {
            if (Host.DebugMode)
            {
                string debugMsg = "{0}, {1}";
                context.Response.AppendHeader("X-OpenUrlRewriter-Debug", string.Format(debugMsg, context.Request.RawUrl, sendToUrl));
            }
            //System.Diagnostics.Debug.WriteLine(context.Request.RawUrl);

            //first strip the querystring, if any
            var queryString = string.Empty;
            sendToUrlLessQString = sendToUrl;
            if ((sendToUrl.IndexOf("?") > 0))
            {
                sendToUrlLessQString = sendToUrl.Substring(0, sendToUrl.IndexOf("?"));
                queryString = sendToUrl.Substring(sendToUrl.IndexOf("?") + 1);
            }

            //grab the file's physical path
            filePath = string.Empty;
            filePath = context.Server.MapPath(sendToUrlLessQString);

            //rewrite the path..
            context.RewritePath(sendToUrlLessQString, string.Empty, queryString);
            //NOTE!  The above RewritePath() overload is only supported in the .NET Framework 1.1
            //If you are using .NET Framework 1.0, use the below form instead:
            //context.RewritePath(sendToUrl);
        }
Beispiel #27
0
 /// <summary>
 /// Rewrites the path to point to the cached image.
 /// </summary>
 /// <param name="context">
 /// The <see cref="HttpContext"/> encapsulating all information about the request.
 /// </param>
 public override void RewritePath(HttpContext context)
 {
     // The cached file is valid so just rewrite the path.
     context.RewritePath(this.virtualCachedFilePath, false);
 }
 /// <summary>
 /// See <see cref="System.Web.HttpContext"/> for a description.
 /// </summary>
 public void RewritePath(string path, bool rebaseClientPath)
 {
     _context.RewritePath(path, rebaseClientPath);
 }
Beispiel #29
0
        //url重定向
        static bool ReWriteUrl(HttpContext context)
        {
            string path = context.Request.Path;

            string filePath = UrlReWriteProvider.Instance().RewriteUrl(path, context.Request.Url.Query);

            if (filePath != null)
            {
                string queryString = null;

                int index = filePath.IndexOf('?');

                if (index >= 0)
                {
                    queryString = (index < (filePath.Length - 1)) ? filePath.Substring(index + 1) : string.Empty;

                    filePath = filePath.Substring(0, index);

                }

                context.RewritePath(filePath, null, queryString);

            }

            return (filePath != null);
        }
Beispiel #30
0
 /// <summary>
 /// Rewrites the incoming image request to the actual handler
 /// </summary>
 /// <param name="context">the context</param>
 /// <param name="url">the url string</param>
 public static void RewriteImagePath(HttpContext context, string url)
 {
     var wr = url.Substring(0, url.IndexOf("/IMAGES/") + 7);
     url = url.Replace(wr, "");
     url = url.Substring(0, url.LastIndexOf(System.IO.Path.GetExtension(url)));
     var npath = string.Format("{0}image.axd?picture={1}", Utils.ApplicationRelativeWebRoot, url);
     context.RewritePath(npath);
 }
Beispiel #31
0
 public override void RewritePath(string path)
 {
     w.RewritePath(path);
 }
Beispiel #32
0
        /// <summary>
        /// Rewrites the page.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="url">The URL string.</param>
        public static void RewritePage(HttpContext context, string url)
        {
            var slug = ExtractTitle(context, url);
            var page =
                Page.Pages.Find(
                    p => slug.Equals(Utils.RemoveIllegalCharacters(p.Slug), StringComparison.OrdinalIgnoreCase));

            if (page != null)
            {
                context.RewritePath(string.Format("{0}page.aspx?id={1}{2}", Utils.ApplicationRelativeWebRoot, page.Id, GetQueryString(context)), false);
            }
        }
Beispiel #33
0
        /// <summary>
        /// The rewrite default.
        /// </summary>
        /// <param name="context">
        /// The context.
        /// </param>
        public static void RewriteDefault(HttpContext context)
        {
            var url = GetUrlWithQueryString(context);
            var page = string.Format("&page={0}", context.Request.QueryString["page"]);

            if (string.IsNullOrEmpty(context.Request.QueryString["page"]))
            {
                page = null;
            }

            if (YearMonthDayRegex.IsMatch(url))
            {
                var match = YearMonthDayRegex.Match(url);
                var year = match.Groups[1].Value;
                var month = match.Groups[2].Value;
                var day = match.Groups[3].Value;
                var date = string.Format("{0}-{1}-{2}", year, month, day);
                url = string.Format("{0}default.aspx?date={1}{2}", Utils.ApplicationRelativeWebRoot, date, page);
            }
            else if (YearMonthRegex.IsMatch(url))
            {
                var match = YearMonthRegex.Match(url);
                var year = match.Groups[1].Value;
                var month = match.Groups[2].Value;
                var path = string.Format("default.aspx?year={0}&month={1}", year, month);
                url = Utils.ApplicationRelativeWebRoot + path + page;
            }
            else if (YearRegex.IsMatch(url))
            {
                var match = YearRegex.Match(url);
                var year = match.Groups[1].Value;
                var path = string.Format("default.aspx?year={0}", year);
                url = Utils.ApplicationRelativeWebRoot + path + page;
            }
            else
            {
                string newUrl = url.Replace("Default.aspx", "default.aspx");  // fixes a casing oddity on Mono
                int defaultStart = url.IndexOf("default.aspx", StringComparison.OrdinalIgnoreCase);
                url = Utils.ApplicationRelativeWebRoot + url.Substring(defaultStart);
            }

            //if (string.IsNullOrEmpty(BlogConfig.FileExtension) && url.Contains("page="))
            //    url = url.Replace("default.aspx?", "");

            context.RewritePath(url, false);
        }
Beispiel #34
0
 public override void RewritePath(string path)
 {
     _context.RewritePath(path);
 }
        private static void Handle404OrException(FriendlyUrlSettings settings, HttpContext context, Exception ex, UrlAction result, bool transfer, bool showDebug)
        {
            //handle Auto-Add Alias
            if (result.Action == ActionType.Output404 && CanAutoAddPortalAlias())
            {
                //Need to determine if this is a real 404 or a possible new alias.
                var portalId = Host.Host.HostPortalID;
                if (portalId > Null.NullInteger)
                {
                    if (string.IsNullOrEmpty(result.DomainName))
                    {
                        result.DomainName = Globals.GetDomainName(context.Request); //parse the domain name out of the request
                    }

                    //Get all the existing aliases
                    var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId).ToList();

                    bool autoaddAlias;
                    bool isPrimary = false;
                    if (!aliases.Any())
                    {
                        autoaddAlias = true;
                        isPrimary = true;
                    }
                    else
                    {
                        autoaddAlias = true;
                        foreach (var alias in aliases)
                        {
                            if (result.DomainName.ToLowerInvariant().IndexOf(alias.HTTPAlias, StringComparison.Ordinal) == 0
                                    && result.DomainName.Length >= alias.HTTPAlias.Length)
                            {
                                autoaddAlias = false;
                                break;
                            }
                        }
                    }

                    if (autoaddAlias)
                    {
                        var portalAliasInfo = new PortalAliasInfo
                                                  {
                                                      PortalID = portalId, 
                                                      HTTPAlias = result.DomainName,
                                                      IsPrimary = isPrimary
                                                  };
                        PortalAliasController.Instance.AddPortalAlias(portalAliasInfo);

                        context.Response.Redirect(context.Request.Url.ToString(), true);
                    }
                }
            }


            if (context != null)
            {
                HttpRequest request = context.Request;
                HttpResponse response = context.Response;
                HttpServerUtility server = context.Server;

                const string errorPageHtmlHeader = @"<html><head><title>{0}</title></head><body>";
                const string errorPageHtmlFooter = @"</body></html>";
                var errorPageHtml = new StringWriter();
                CustomErrorsSection ceSection = null;
                //876 : security catch for custom error reading
                try
                {
                    ceSection = (CustomErrorsSection) WebConfigurationManager.GetSection("system.web/customErrors");
                }
// ReSharper disable EmptyGeneralCatchClause
                catch (Exception)
// ReSharper restore EmptyGeneralCatchClause
                {
                    //on some medium trust environments, this will throw an exception for trying to read the custom Errors
                    //do nothing
                }

                /* 454 new 404/500 error handling routine */
                bool useDNNTab = false;
                int errTabId = -1;
                string errUrl = null;
                string status = "";
                bool isPostback = false;
                if (settings != null)
                {
                    if (request.RequestType == "POST")
                    {
                        isPostback = true;
                    }
                    if (result != null && ex != null)
                    {
                        result.DebugMessages.Add("Exception: " + ex.Message);
                        result.DebugMessages.Add("Stack Trace: " + ex.StackTrace);
                        if (ex.InnerException != null)
                        {
                            result.DebugMessages.Add("Inner Ex : " + ex.InnerException.Message);
                            result.DebugMessages.Add("Stack Trace: " + ex.InnerException.StackTrace);
                        }
                        else
                        {
                            result.DebugMessages.Add("Inner Ex : null");
                        }
                    }
                    string errRH;
                    string errRV;
                    int statusCode;
                    if (result != null && result.Action != ActionType.Output404)
                    {
                        //output everything but 404 (usually 500)
                        if (settings.TabId500 > -1) //tabid specified for 500 error page, use that
                        {
                            useDNNTab = true;
                            errTabId = settings.TabId500;
                        }
                        errUrl = settings.Url500;
                        errRH = "X-UrlRewriter-500";
                        errRV = "500 Rewritten to {0} : {1}";
                        statusCode = 500;
                        status = "500 Internal Server Error";
                    }
                    else //output 404 error 
                    {
                        if (settings.TabId404 > -1) //if the tabid is specified for a 404 page, then use that
                        {
                            useDNNTab = true;
                            errTabId = settings.TabId404;
                        }
                        if (!String.IsNullOrEmpty(settings.Regex404))
                            //with 404 errors, there's an option to catch certain urls and use an external url for extra processing.
                        {
                            try
                            {
                                //944 : check the original Url in case the requested Url has been rewritten before discovering it's a 404 error
                                string requestedUrl = request.Url.ToString();
                                if (result != null && string.IsNullOrEmpty(result.OriginalPath) == false)
                                {
                                    requestedUrl = result.OriginalPath;
                                }
                                if (Regex.IsMatch(requestedUrl, settings.Regex404, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant))
                                {
                                    useDNNTab = false;
                                        //if we have a match in the 404 regex value, then don't use the tabid
                                }
                            }
                            catch (Exception regexEx)
                            {
                                //.some type of exception : output in response header, and go back to using the tabid 
                                response.AppendHeader("X-UrlRewriter-404Exception", regexEx.Message);
                            }
                        }
                        errUrl = settings.Url404;
                        errRH = "X-UrlRewriter-404";
                        errRV = "404 Rewritten to {0} : {1} : Reason {2}";
                        status = "404 Not Found";
                        statusCode = 404;
                    }

                    // check for 404 logging
                    if ((result == null || result.Action == ActionType.Output404))
                    {
                        //Log 404 errors to Event Log
                        UrlRewriterUtils.Log404(request, settings, result);
                    }
                    //912 : use unhandled 404 switch
                    string reason404 = null;
                    bool unhandled404 = true;
                    if (useDNNTab && errTabId > -1)
                    {
                        unhandled404 = false; //we're handling it here
                        TabInfo errTab = TabController.Instance.GetTab(errTabId, result.PortalId, true);
                        if (errTab != null)
                        {
                            bool redirect = false;
                            //ok, valid tabid.  what we're going to do is to load up this tab via a rewrite of the url, and then change the output status
                            string reason = "Not Found";
                            if (result != null)
                            {
                                reason = result.Reason.ToString();
                            }
                            response.AppendHeader(errRH, string.Format(errRV, "DNN Tab",
                                                                errTab.TabName + "(Tabid:" + errTabId.ToString() + ")",
                                                                reason));
                            //show debug messages even if in debug mode
                            if (context != null && response != null && result != null && showDebug)
                            {
                                ShowDebugData(context, result.OriginalPath, result, null);
                            }
                            if (!isPostback)
                            {
                                response.ClearContent();
                                response.StatusCode = statusCode;
                                response.Status = status;
                            }
                            else
                            {
                                redirect = true;
                                    //redirect postbacks as you can't postback successfully to a server.transfer
                            }
                            errUrl = Globals.glbDefaultPage + TabIndexController.CreateRewritePath(errTab.TabID, "");
                            //have to update the portal settings with the new tabid
                            PortalSettings ps = null;
                            if (context != null && context.Items != null)
                            {
                                if (context.Items.Contains("PortalSettings"))
                                {
                                    ps = (PortalSettings) context.Items["PortalSettings"];
                                    context.Items.Remove("PortalSettings"); //nix it from the context
                                }
                            }
                            if (ps != null && ps.PortalAlias != null)
                            {
                                ps = new PortalSettings(errTabId, ps.PortalAlias);
                            }
                            else
                            {
                                if (result.HttpAlias != null && result.PortalId > -1)
                                {
                                    PortalAliasInfo pa = PortalAliasController.Instance.GetPortalAlias(result.HttpAlias, result.PortalId);
                                    ps = new PortalSettings(errTabId, pa);
                                }
                                else
                                {
                                    //912 : handle 404 when no valid portal can be identified
                                    //results when iis is configured to handle portal alias, but 
                                    //DNN isn't.  This always returns 404 because a multi-portal site
                                    //can't just show the 404 page of the host site.
                                    ArrayList portals = PortalController.Instance.GetPortals();
                                    if (portals != null && portals.Count == 1)
                                    {
                                        //single portal install, load up portal settings for this portal
                                        var singlePortal = (PortalInfo) portals[0];
                                        //list of aliases from database
                                        var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(singlePortal.PortalID).ToList();
                                        //list of aliases from Advanced Url settings
                                        List<string> chosen = aliases.GetAliasesForPortalId(singlePortal.PortalID);
                                        PortalAliasInfo useFor404 = null;
                                        //go through all aliases and either get the first valid one, or the first 
                                        //as chosen in the advanced url management settings
                                        foreach (var pa in aliases)
                                        {
                                            if (useFor404 == null)
                                            {
                                                useFor404 = pa; //first one by default
                                            }

                                            //matching?
                                            if (chosen != null && chosen.Count > 0)
                                            {
                                                if (chosen.Contains(pa.HTTPAlias))
                                                {
                                                    useFor404 = pa;
                                                }
                                            }
                                            else
                                            {
                                                break; //no further checking
                                            }
                                        }
                                        //now configure that as the portal settings
                                        if (useFor404 != null)
                                        {
                                            //create portal settings context for identified portal alias in single portal install
                                            ps = new PortalSettings(errTabId, useFor404);
                                        }
                                    }
                                    else
                                    {
                                        reason404 = "Requested domain name is not configured as valid website";
                                        unhandled404 = true;
                                    }
                                }
                            }
                            if (ps != null)
                            {
                                //re-add the context items portal settings back in
                                context.Items.Add("PortalSettings", ps);
                            }
                            if (redirect)
                            {
                                errUrl = TestableGlobals.Instance.NavigateURL();
                                response.Redirect(errUrl, true); //redirect and end response.  
                                //It will mean the user will have to postback again, but it will work the second time
                            }
                            else
                            {
                                if (transfer)
                                {
                                    //execute a server transfer to the default.aspx?tabid=xx url
                                    //767 : object not set error on extensionless 404 errors
                                    if (context.User == null)
                                    {
                                        context.User = Thread.CurrentPrincipal;
                                    }
                                    response.TrySkipIisCustomErrors = true;
                                    //881 : spoof the basePage object so that the client dependency framework
                                    //is satisfied it's working with a page-based handler
                                    IHttpHandler spoofPage = new CDefault();
                                    context.Handler = spoofPage;
                                    server.Transfer("~/" + errUrl, true);
                                }
                                else
                                {
                                    context.RewritePath("~/Default.aspx", false);
                                    response.TrySkipIisCustomErrors = true;
                                    response.Status = "404 Not Found";
                                    response.StatusCode = 404;
                                }
                            }
                        }
                    }
                    //912 : change to new if statement to handle cases where the TabId404 couldn't be handled correctly
                    if (unhandled404)
                    {
                        //proces the error on the external Url by rewriting to the external url
                        if (!String.IsNullOrEmpty(errUrl))
                        {
                            response.ClearContent();
                            response.TrySkipIisCustomErrors = true;
                            string reason = "Not Found";
                            if (result != null)
                            {
                                reason = result.Reason.ToString();
                            }
                            response.AppendHeader(errRH, string.Format(errRV, "Url", errUrl, reason));
                            if (reason404 != null)
                            {
                                response.AppendHeader("X-Url-Master-404-Data", reason404);
                            }
                            response.StatusCode = statusCode;
                            response.Status = status;
                            server.Transfer("~/" + errUrl, true);
                        }
                        else
                        {
                            errorPageHtml.Write(status + "<br>The requested Url does not return any valid content.");
                            if (reason404 != null)
                            {
                                errorPageHtml.Write(status + "<br>" + reason404);
                            }
                            errorPageHtml.Write("<div style='font-weight:bolder'>Administrators</div>");
                            errorPageHtml.Write("<div>Change this message by configuring a specific 404 Error Page or Url for this website.</div>");

                            //output a reason for the 404
                            string reason = "";
                            if (result != null)
                            {
                                reason = result.Reason.ToString();
                            }
                            if (!string.IsNullOrEmpty(errRH) && !string.IsNullOrEmpty(reason))
                            {
                                response.AppendHeader(errRH, reason);
                            }
                            response.StatusCode = statusCode;
                            response.Status = status;
                        }
                    }
                }
                else
                {
                    //fallback output if not valid settings
                    if (result != null && result.Action == ActionType.Output404)
                    {
                        //don't restate the requested Url to prevent cross site scripting
                        errorPageHtml.Write("404 Not Found<br>The requested Url does not return any valid content.");
                        response.StatusCode = 404;
                        response.Status = "404 Not Found";
                    }
                    else
                    {
                        //error, especially if invalid result object

                        errorPageHtml.Write("500 Server Error<br><div style='font-weight:bolder'>An error occured during processing : if possible, check the event log of the server</div>");
                        response.StatusCode = 500;
                        response.Status = "500 Internal Server Error";
                        if (result != null)
                        {
                            result.Action = ActionType.Output500;
                        }
                    }
                }

                if (ex != null)
                {
                    if (context != null)
                    {
                        if (context.Items.Contains("UrlRewrite:Exception") == false)
                        {
                            context.Items.Add("UrlRewrite:Exception", ex.Message);
                            context.Items.Add("UrlRewrite:StackTrace", ex.StackTrace);
                        }
                    }

                    if (ceSection != null && ceSection.Mode == CustomErrorsMode.Off)
                    {
                        errorPageHtml.Write(errorPageHtmlHeader);
                        errorPageHtml.Write("<div style='font-weight:bolder'>Exception:</div><div>" + ex.Message + "</div>");
                        errorPageHtml.Write("<div style='font-weight:bolder'>Stack Trace:</div><div>" + ex.StackTrace + "</div>");
                        errorPageHtml.Write("<div style='font-weight:bolder'>Administrators</div>");
                        errorPageHtml.Write("<div>You can see this exception because the customErrors attribute in the web.config is set to 'off'.  Change this value to 'on' or 'RemoteOnly' to show Error Handling</div>");
                        try
                        {
                            if (errUrl != null && errUrl.StartsWith("~"))
                            {
                                errUrl = VirtualPathUtility.ToAbsolute(errUrl);
                            }
                        }
                        finally
                        {
                            if (errUrl != null)
                            {
                                errorPageHtml.Write("<div>The error handling would have shown this page : <a href='" + errUrl + "'>" + errUrl + "</a></div>");
                            }
                            else
                            {
                                errorPageHtml.Write("<div>The error handling could not determine the correct page to show.</div>");
                            }
                        }
                    }
                }

                string errorPageHtmlBody = errorPageHtml.ToString();
                if (errorPageHtmlBody.Length > 0)
                {
                    response.Write(errorPageHtmlHeader);
                    response.Write(errorPageHtmlBody);
                    response.Write(errorPageHtmlFooter);
                }
                if (ex != null)
                {
                    UrlRewriterUtils.LogExceptionInRequest(ex, status, result);
                }
            }
        }
Beispiel #36
0
        /// <summary>
        /// 通过实现 IHttpHandler 接口的自定义 HttpHandler 启用 HTTP Web 请求的处理。
        /// </summary>
        /// <param name="context">HttpContext 对象,它提供对用于为 HTTP 请求提供服务的内部服务器对象(如 Request、Response、Session 和 Server)的引用。</param>
        public override void ProcessRequest(System.Web.HttpContext context)
        {
            base.ProcessRequest(context);

            string path = context.Server.MapPath(this.RealPath);

            if (System.IO.File.Exists(path))
            {
                switch (this.Config.Action)
                {
                case "none":
                    PageParser.GetCompiledPageInstance(this.RealPath, path, context).ProcessRequest(context);
                    break;

                case "rewrite":
                    context.RewritePath(context.Request.Path, this.PathInfo, this.QueryString);
                    PageParser.GetCompiledPageInstance(this.RealPath, path, context).ProcessRequest(context);
                    break;

                case "cache_static":
                //一般静态文件缓存.
                case "cache_static_news":
                //新闻查看静态文件缓存
                case "cache_static_pub":
                    //蒲点查看静态文件缓存
                    string   filePath       = context.Server.MapPath(this.FilePath);
                    FileInfo fileInfo       = new FileInfo(filePath);
                    FileInfo fileInfoSource = new FileInfo(path);
                    bool     toRebuild      = false;
                    if (!fileInfo.Exists ||
                        (this.Config.TimeSpan.Ticks > 0 &&
                         fileInfo.LastWriteTime.Add(this.Config.TimeSpan) < DateTime.Now) ||
                        fileInfoSource.LastWriteTime > fileInfo.LastWriteTime)
                    {
                        toRebuild = true;
                    }

                    if (toRebuild)
                    {
                        context.RewritePath(context.Request.Path, this.PathInfo, this.QueryString);

                        switch (this.Config.Action)
                        {
                        case "cache_static_news":
                            #region 新闻查看静态文件缓存

                            /*long newsId			= 0;
                             * if (context.Request.QueryString["newsId"] != null &&
                             *      context.Request.QueryString["newsId"].Length != 0)
                             * {
                             *      newsId			= Convert.ToInt64(context.Request.QueryString["newsId"]	, 10);
                             *
                             * }
                             * DataModel.News.News newsItem	= null;
                             *
                             * if (context.Items[News.PageBaseNewsView.CONTEXT_KEY_NEWS] == null &&
                             *      newsId > 0)
                             * {
                             *      context.Items[News.PageBaseNewsView.CONTEXT_KEY_NEWS]	= DAL.News.News.Get(newsId);
                             * }
                             *
                             * newsItem	= context.Items[News.PageBaseNewsView.CONTEXT_KEY_NEWS] as DataModel.News.News;
                             *
                             * if (newsItem == null)
                             * {
                             *      context.Response.Redirect(this.Error404Url	, true);
                             * }
                             *
                             * if (newsItem != null &&
                             *      newsItem.CheckState == DataModel.News.CheckState.Passed &&
                             *      newsItem.IsView)
                             * {
                             *      PageParser.GetCompiledPageInstance(this.RealPath	, path , context).ProcessRequest(context);
                             *
                             *      this.SetStaticFilter(context , filePath);
                             *      return;
                             * }
                             * else
                             * {
                             *      context.Response.Redirect(this.Error404Url	, true);
                             *      return;
                             * }*/
                            #endregion
                        case "cache_static":
                        default:
                            #region 一般静态文件缓存
                            PageParser.GetCompiledPageInstance(this.RealPath, path, context).ProcessRequest(context);
                            this.SetStaticFilter(context, filePath);
                            return;

                            #endregion
                        }
                    }
                    else
                    {
                        //直接调用静态文件
                        context.Response.WriteFile(filePath);
                        context.Response.End();
                    }
                    break;
                }
            }
            else
            {
                context.Response.Redirect(this.Error404Url, true);
            }
        }