MYBLOG

欢迎来到小马哥的个人博客~

[原创]URLRewriter读取真实html文件

2020-03-08学海无涯

URLRewriter.dll,相信做过asp.net的很多人都用到过,我也一直用这个东西,挺好用的。最近项目有个需求,需要对网站商品详情页生成静态。好吧,咱就写呗,先写生成静态页面,但是生成静态页面功能写完了,但是却发现URLRewriter并不会因为有真实的html文件,而去访问真实的html,而是还是走的aspx。话罢,那咋办捏,先把URLRewriter给反编译了,看看这东西里面咋写的,于是乎反编译之后得到以下目录结构

好嘛,接下来读读代码吧。

接下来,笔者改写了“ModuleRewriter.cs”文件,其改写之后的代码如下


/// <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)
        {
            string FileName = HttpContext.Current.Server.MapPath(requestedPath);
            if (string.IsNullOrEmpty(Path.GetExtension(FileName)))
            {
                FileName += "index.html";
            }
            if (!File.Exists(FileName))
            {
                // log information to the Trace object.
                app.Context.Trace.Write("ModuleRewriter", "Entering ModuleRewriter");

                // 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));

                        // log rewriting information to the Trace object
                        app.Context.Trace.Write("ModuleRewriter", "Rewriting URL to " + sendToUrl);

                        // Rewrite the URL
                        RewriterUtils.RewriteUrl(app.Context, sendToUrl);
                        break;		// exit the for loop
                    }
                }
                // Log information to the Trace object
                app.Context.Trace.Write("ModuleRewriter", "Exiting ModuleRewriter");
            }
           
        }
其实,无非就是加了个文件判断,判断下文件是否真实存在。OK,问题解决!~