利用UrlRewrite,asp.net动态生成htm页面
前段时间做项目,一直都在寻找一种动态生成htm页面的方法,要求配置简单,和项目无关。
功夫不负有心人,终于被我找到了,只需要在web.config中进行简单配置,就可以达到动态生成静态页面的效果,同时又不影响Url重定向。web.config中需要注意的配置节为<configuration>、<RewriteConfig>、<httpModules>、<httpHandlers>,在这些配置节里边都有注释,容易看懂。
 <?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
 <!--
<!-- 
 注意: 除了手动编辑此文件以外,您还可以使用
    注意: 除了手动编辑此文件以外,您还可以使用 
 Web 管理工具来配置应用程序的设置。可以使用 Visual Studio 中的
    Web 管理工具来配置应用程序的设置。可以使用 Visual Studio 中的
 “网站”->“Asp.Net 配置”选项。
     “网站”->“Asp.Net 配置”选项。
 设置和注释的完整列表在
    设置和注释的完整列表在 
 machine.config.comments 中,该文件通常位于
    machine.config.comments 中,该文件通常位于 
 \Windows\Microsoft.Net\Framework\v2.x\Config 中
    \Windows\Microsoft.Net\Framework\v2.x\Config 中
 -->
-->
 <configuration>
<configuration>

 <!-- RUL重写开始 -->
  <!-- RUL重写开始 -->
 <configSections>
  <configSections>
 <section name="RewriterConfig" type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter"/>
    <section name="RewriterConfig" type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter"/>
 </configSections>
  </configSections>
 <RewriterConfig>
  <RewriterConfig>
 <Rules>
    <Rules>
 <!--地址重写规则-->
      <!--地址重写规则-->
 <!--首页,定位到静态页面-->
      <!--首页,定位到静态页面-->
 <RewriterRule>
      <RewriterRule>
 <Type>Static</Type>
        <Type>Static</Type>
 <LookFor>~/Default\.aspx</LookFor>
        <LookFor>~/Default\.aspx</LookFor>
 <SendTo>~/Default.htm</SendTo>
        <SendTo>~/Default.htm</SendTo>
 </RewriterRule>
      </RewriterRule>
 <!--二级页面,定位到动态页面-->
      <!--二级页面,定位到动态页面-->
 <RewriterRule>
      <RewriterRule>
 <Type>Dynamic</Type>
        <Type>Dynamic</Type>
 <LookFor>~/List\.aspx</LookFor>
        <LookFor>~/List\.aspx</LookFor>
 <SendTo>~/Show.aspx</SendTo>
        <SendTo>~/Show.aspx</SendTo>
 </RewriterRule>
      </RewriterRule>
 </Rules>
    </Rules>
 </RewriterConfig>
  </RewriterConfig>
 <!-- RUL重写结束 -->
  <!-- RUL重写结束 -->

 <appSettings/>
  <appSettings/>
 <connectionStrings/>
  <connectionStrings/>
 <system.web>
  <system.web>
 <!--
    <!-- 
 设置 compilation debug="true" 将调试符号插入
            设置 compilation debug="true" 将调试符号插入
 已编译的页面中。但由于这会
            已编译的页面中。但由于这会 
 影响性能,因此只在开发过程中将此值
            影响性能,因此只在开发过程中将此值 
 设置为 true。
            设置为 true。
 -->
        -->
 <httpModules>
    <httpModules>
 <!--URL重写-->
      <!--URL重写-->
 <add type="URLRewriter.ModuleRewriter, URLRewriter" name="ModuleRewriter" />
      <add type="URLRewriter.ModuleRewriter, URLRewriter" name="ModuleRewriter" />
 </httpModules>
    </httpModules>
 
    
 <httpHandlers>
    <httpHandlers>
 <!--生成静态页面-->
      <!--生成静态页面-->
 <add verb="*" path="*.aspx" validate="false" type="URLRewriter.RewriterFactoryHandler, URLRewriter"/>
      <add verb="*" path="*.aspx" validate="false" type="URLRewriter.RewriterFactoryHandler, URLRewriter"/>
 </httpHandlers>
    </httpHandlers>
 
    
 <compilation debug="false" />
    <compilation debug="false" />
 <!--
    <!--
 通过 <authentication> 节可以配置 ASP.NET 使用的
            通过 <authentication> 节可以配置 ASP.NET 使用的 
 安全身份验证模式,
            安全身份验证模式,
 以标识传入的用户。
            以标识传入的用户。 
 -->
        -->
 <authentication mode="Forms" />
    <authentication mode="Forms" />
 <!--
    <!--
 如果在执行请求的过程中出现未处理的错误,
            如果在执行请求的过程中出现未处理的错误,
 则通过 <customErrors> 节可以配置相应的处理步骤。具体说来,
            则通过 <customErrors> 节可以配置相应的处理步骤。具体说来,
 开发人员通过该节可以配置
            开发人员通过该节可以配置
 要显示的 html 错误页
            要显示的 html 错误页
 以代替错误堆栈跟踪。
            以代替错误堆栈跟踪。

 <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
 <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="403" redirect="NoAccess.htm" />
 <error statusCode="404" redirect="FileNotFound.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
 </customErrors>
        </customErrors>
 -->
        -->
 <globalization requestEncoding="utf-8" responseEncoding="utf-8"/>
    <globalization requestEncoding="utf-8" responseEncoding="utf-8"/>
 </system.web>
  </system.web>
 </configuration>
</configuration>
 两个关键的类是ModuleRewriter和CreateHtmFactoryHandler
两个关键的类是ModuleRewriter和CreateHtmFactoryHandler
ModuleRewriter类用于Url重定向,代码如下:

 using System;
using System;
 using System.Text.RegularExpressions;
using System.Text.RegularExpressions;
 using System.Configuration;
using System.Configuration;
 using URLRewriter.Config;
using URLRewriter.Config;
 using System.Data;
using System.Data;
 using System.Web;
using System.Web;
 using System.Web.UI;
using System.Web.UI;

 namespace URLRewriter
namespace URLRewriter
 {
{
 /// <summary>
    /// <summary>
 /// Provides a rewriting HttpModule.
    /// Provides a rewriting HttpModule.
 /// </summary>
    /// </summary>
 public class ModuleRewriter : BaseModuleRewriter
    public class ModuleRewriter : BaseModuleRewriter
 {
    {
 /// <summary>
        /// <summary>
 /// This method is called during the module's BeginRequest event.
        /// This method is called during the module's BeginRequest event.
 /// </summary>
        /// </summary>
 /// <param name="requestedRawUrl">The RawUrl being requested (includes path and querystring).</param>
        /// <param name="requestedRawUrl">The RawUrl being requested (includes path and querystring).</param>
 /// <param name="app">The HttpApplication instance.</param>
        /// <param name="app">The HttpApplication instance.</param>
 protected override void Rewrite(string requestedPath, System.Web.HttpApplication app)
        protected override void Rewrite(string requestedPath, System.Web.HttpApplication app)
 {
        {
 //只对文件后缀为aspx页面有效
            //只对文件后缀为aspx页面有效
 if (requestedPath.IndexOf(".aspx") != -1)
            if (requestedPath.IndexOf(".aspx") != -1)
 {
            {
 HttpContext httpContext = app.Context;
                HttpContext httpContext = app.Context;

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

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

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

 // See if a match is found
                    // See if a match is found
 if (re.IsMatch(requestedPath))
                    if (re.IsMatch(requestedPath))
 {
                    {
 //aspx页面重定向到htm页面且http数据传输方式为“GET”
                        //aspx页面重定向到htm页面且http数据传输方式为“GET”
 if (rules[i].Type == WebType.Static && app.Context.Request.RequestType == "GET")
                        if (rules[i].Type == WebType.Static && app.Context.Request.RequestType == "GET")
 {
                        {
 //静态页面路径
                            //静态页面路径
 string htmlWeb = RewriterUtils.ResolveUrl(httpContext.Request.ApplicationPath, rules[i].SendTo);
                            string htmlWeb = RewriterUtils.ResolveUrl(httpContext.Request.ApplicationPath, rules[i].SendTo);
 //静态页面的最后修改时间
                            //静态页面的最后修改时间
 DateTime dt = System.IO.File.GetLastWriteTime(httpContext.Server.MapPath(htmlWeb));
                            DateTime dt = System.IO.File.GetLastWriteTime(httpContext.Server.MapPath(htmlWeb));
 //当前时间和静态页面生成时间对比,如果时间小于一个小时,重定向到静态页面
                            //当前时间和静态页面生成时间对比,如果时间小于一个小时,重定向到静态页面
 if (DateTime.Compare(DateTime.Now.AddHours(-1), dt) <= 0)
                            if (DateTime.Compare(DateTime.Now.AddHours(-1), dt) <= 0)
 {
                            {
 requestedPath = htmlWeb;
                                requestedPath = htmlWeb;
 }
                            }
 }
                        }
 else
                        else
 {
                        {
 requestedPath = rules[i].SendTo;
                            requestedPath = rules[i].SendTo;
 }
                        }

 // Rewrite the URL
                        // Rewrite the URL
 RewriterUtils.RewriteUrl(httpContext, requestedPath);
                        RewriterUtils.RewriteUrl(httpContext, requestedPath);
 break;        // exit the for loop
                        break;        // exit the for loop
 }
                    }
 }
                }
 }
            }
 }
        }

 }
    }
 }
}
 CreateHtmFactoryHandler类用于生成静态页面,代码如下:
CreateHtmFactoryHandler类用于生成静态页面,代码如下:

 using System;
using System;
 using System.IO;
using System.IO;
 using System.Web.UI;
using System.Web.UI;
 using System.Web;
using System.Web;
 using URLRewriter.Config;
using URLRewriter.Config;
 using System.Configuration;
using System.Configuration;
 using System.Text.RegularExpressions;
using System.Text.RegularExpressions;

 namespace URLRewriter
namespace URLRewriter
 {
{
 /// <summary>
    /// <summary>
 /// 依据web.config配置信息,生成静态页面
    /// 依据web.config配置信息,生成静态页面
 /// </summary>
    /// </summary>
 public class CreateHtmFactoryHandler : IHttpHandlerFactory
    public class CreateHtmFactoryHandler : IHttpHandlerFactory
 {
    {
 /// <summary>
        /// <summary>
 ///
        /// 
 /// </summary>
        /// </summary>
 /// <param name="context">HttpContext 类的实例,它提供对用于为 HTTP 请求提供服务的内部服务器对象(如 Request、Response、Session 和 Server)的引用</param>
        /// <param name="context">HttpContext 类的实例,它提供对用于为 HTTP 请求提供服务的内部服务器对象(如 Request、Response、Session 和 Server)的引用</param>
 /// <param name="requestType">客户端使用的 HTTP 数据传输方法(GET 或 POST)</param>
        /// <param name="requestType">客户端使用的 HTTP 数据传输方法(GET 或 POST)</param>
 /// <param name="url">所请求资源的 RawUrl。</param>
        /// <param name="url">所请求资源的 RawUrl。</param>
 /// <param name="pathTranslated">所请求资源的 PhysicalApplicationPath</param>
        /// <param name="pathTranslated">所请求资源的 PhysicalApplicationPath</param>
 /// <returns>返回实现 IHttpHandler 接口的类的实例</returns>
        /// <returns>返回实现 IHttpHandler 接口的类的实例</returns>
 public virtual IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
        public virtual IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
 {
        {
 if (requestType == "GET")
            if (requestType == "GET")
 {
            {
 // get the configuration rules
                // get the configuration rules
 RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;
                RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;

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

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

 // See if a match is found
                    // See if a match is found
 if (re.IsMatch(url) && rules[i].Type == WebType.Static)
                    if (re.IsMatch(url) && rules[i].Type == WebType.Static)
 {
                    {
 //得到要生成的静态页面的物理路径
                        //得到要生成的静态页面的物理路径
 string physicsWeb = context.Server.MapPath(RewriterUtils.ResolveUrl(context.Request.ApplicationPath, rules[i].SendTo));
                        string physicsWeb = context.Server.MapPath(RewriterUtils.ResolveUrl(context.Request.ApplicationPath, rules[i].SendTo));
 //设定Response筛选器
                        //设定Response筛选器
 context.Response.Filter = new ResponseFilter(context.Response.Filter, physicsWeb);
                        context.Response.Filter = new ResponseFilter(context.Response.Filter, physicsWeb);
 break;
                        break;
 }
                    }
 }
                }
 }
            }
 //得到编译实例
            //得到编译实例
 return PageParser.GetCompiledPageInstance(url, pathTranslated, context);
            return PageParser.GetCompiledPageInstance(url, pathTranslated, context);
 }
        }

 public virtual void ReleaseHandler(IHttpHandler handler)
        public virtual void ReleaseHandler(IHttpHandler handler)
 {
        {
 }
        }
 }
    }
 }
}
 以上是两个主要的类,还有一些辅助的类,我把测试项目附上,里边有源代码和示例。
以上是两个主要的类,还有一些辅助的类,我把测试项目附上,里边有源代码和示例。
点击这里下载:源代码和示例
声明一下,我是在修改一个开源的项目(UrlRewrite)来实现上述功能。有关UrlRewrite介绍,请看这里,ASP.NET 中执行 URL 重写。
功夫不负有心人,终于被我找到了,只需要在web.config中进行简单配置,就可以达到动态生成静态页面的效果,同时又不影响Url重定向。web.config中需要注意的配置节为<configuration>、<RewriteConfig>、<httpModules>、<httpHandlers>,在这些配置节里边都有注释,容易看懂。
 <?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?> <!--
<!--  注意: 除了手动编辑此文件以外,您还可以使用
    注意: 除了手动编辑此文件以外,您还可以使用  Web 管理工具来配置应用程序的设置。可以使用 Visual Studio 中的
    Web 管理工具来配置应用程序的设置。可以使用 Visual Studio 中的 “网站”->“Asp.Net 配置”选项。
     “网站”->“Asp.Net 配置”选项。 设置和注释的完整列表在
    设置和注释的完整列表在  machine.config.comments 中,该文件通常位于
    machine.config.comments 中,该文件通常位于  \Windows\Microsoft.Net\Framework\v2.x\Config 中
    \Windows\Microsoft.Net\Framework\v2.x\Config 中 -->
--> <configuration>
<configuration>
 <!-- RUL重写开始 -->
  <!-- RUL重写开始 --> <configSections>
  <configSections> <section name="RewriterConfig" type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter"/>
    <section name="RewriterConfig" type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter"/> </configSections>
  </configSections> <RewriterConfig>
  <RewriterConfig> <Rules>
    <Rules> <!--地址重写规则-->
      <!--地址重写规则--> <!--首页,定位到静态页面-->
      <!--首页,定位到静态页面--> <RewriterRule>
      <RewriterRule> <Type>Static</Type>
        <Type>Static</Type> <LookFor>~/Default\.aspx</LookFor>
        <LookFor>~/Default\.aspx</LookFor> <SendTo>~/Default.htm</SendTo>
        <SendTo>~/Default.htm</SendTo> </RewriterRule>
      </RewriterRule> <!--二级页面,定位到动态页面-->
      <!--二级页面,定位到动态页面--> <RewriterRule>
      <RewriterRule> <Type>Dynamic</Type>
        <Type>Dynamic</Type> <LookFor>~/List\.aspx</LookFor>
        <LookFor>~/List\.aspx</LookFor> <SendTo>~/Show.aspx</SendTo>
        <SendTo>~/Show.aspx</SendTo> </RewriterRule>
      </RewriterRule> </Rules>
    </Rules> </RewriterConfig>
  </RewriterConfig> <!-- RUL重写结束 -->
  <!-- RUL重写结束 -->
 <appSettings/>
  <appSettings/> <connectionStrings/>
  <connectionStrings/> <system.web>
  <system.web> <!--
    <!--  设置 compilation debug="true" 将调试符号插入
            设置 compilation debug="true" 将调试符号插入 已编译的页面中。但由于这会
            已编译的页面中。但由于这会  影响性能,因此只在开发过程中将此值
            影响性能,因此只在开发过程中将此值  设置为 true。
            设置为 true。 -->
        --> <httpModules>
    <httpModules> <!--URL重写-->
      <!--URL重写--> <add type="URLRewriter.ModuleRewriter, URLRewriter" name="ModuleRewriter" />
      <add type="URLRewriter.ModuleRewriter, URLRewriter" name="ModuleRewriter" /> </httpModules>
    </httpModules> 
     <httpHandlers>
    <httpHandlers> <!--生成静态页面-->
      <!--生成静态页面--> <add verb="*" path="*.aspx" validate="false" type="URLRewriter.RewriterFactoryHandler, URLRewriter"/>
      <add verb="*" path="*.aspx" validate="false" type="URLRewriter.RewriterFactoryHandler, URLRewriter"/> </httpHandlers>
    </httpHandlers> 
     <compilation debug="false" />
    <compilation debug="false" /> <!--
    <!-- 通过 <authentication> 节可以配置 ASP.NET 使用的
            通过 <authentication> 节可以配置 ASP.NET 使用的  安全身份验证模式,
            安全身份验证模式, 以标识传入的用户。
            以标识传入的用户。  -->
        --> <authentication mode="Forms" />
    <authentication mode="Forms" /> <!--
    <!-- 如果在执行请求的过程中出现未处理的错误,
            如果在执行请求的过程中出现未处理的错误, 则通过 <customErrors> 节可以配置相应的处理步骤。具体说来,
            则通过 <customErrors> 节可以配置相应的处理步骤。具体说来, 开发人员通过该节可以配置
            开发人员通过该节可以配置 要显示的 html 错误页
            要显示的 html 错误页 以代替错误堆栈跟踪。
            以代替错误堆栈跟踪。
 <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm"> <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="403" redirect="NoAccess.htm" /> <error statusCode="404" redirect="FileNotFound.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" /> </customErrors>
        </customErrors> -->
        --> <globalization requestEncoding="utf-8" responseEncoding="utf-8"/>
    <globalization requestEncoding="utf-8" responseEncoding="utf-8"/> </system.web>
  </system.web> </configuration>
</configuration>
ModuleRewriter类用于Url重定向,代码如下:

 using System;
using System; using System.Text.RegularExpressions;
using System.Text.RegularExpressions; using System.Configuration;
using System.Configuration; using URLRewriter.Config;
using URLRewriter.Config; using System.Data;
using System.Data; using System.Web;
using System.Web; using System.Web.UI;
using System.Web.UI;
 namespace URLRewriter
namespace URLRewriter {
{ /// <summary>
    /// <summary> /// Provides a rewriting HttpModule.
    /// Provides a rewriting HttpModule. /// </summary>
    /// </summary> public class ModuleRewriter : BaseModuleRewriter
    public class ModuleRewriter : BaseModuleRewriter {
    { /// <summary>
        /// <summary> /// This method is called during the module's BeginRequest event.
        /// This method is called during the module's BeginRequest event. /// </summary>
        /// </summary> /// <param name="requestedRawUrl">The RawUrl being requested (includes path and querystring).</param>
        /// <param name="requestedRawUrl">The RawUrl being requested (includes path and querystring).</param> /// <param name="app">The HttpApplication instance.</param>
        /// <param name="app">The HttpApplication instance.</param> protected override void Rewrite(string requestedPath, System.Web.HttpApplication app)
        protected override void Rewrite(string requestedPath, System.Web.HttpApplication app) {
        { //只对文件后缀为aspx页面有效
            //只对文件后缀为aspx页面有效 if (requestedPath.IndexOf(".aspx") != -1)
            if (requestedPath.IndexOf(".aspx") != -1) {
            { HttpContext httpContext = app.Context;
                HttpContext httpContext = app.Context;
 // get the configuration rules
                // get the configuration rules RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;
                RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;
 // iterate through each rule
                // iterate through each rule
 for (int i = 0; i < rules.Count; i++)
                for (int i = 0; i < rules.Count; i++) {
                { // get the pattern to look for, and Resolve the Url (convert ~ into the appropriate directory)
                    // get the pattern to look for, and Resolve the Url (convert ~ into the appropriate directory) string lookFor = "^" + RewriterUtils.ResolveUrl(httpContext.Request.ApplicationPath, rules[i].LookFor) + "$";
                    string lookFor = "^" + RewriterUtils.ResolveUrl(httpContext.Request.ApplicationPath, rules[i].LookFor) + "$";
 // Create a regex (note that IgnoreCase is set
                    // Create a regex (note that IgnoreCase is set )
) Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);
                    Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);
 // See if a match is found
                    // See if a match is found if (re.IsMatch(requestedPath))
                    if (re.IsMatch(requestedPath)) {
                    { //aspx页面重定向到htm页面且http数据传输方式为“GET”
                        //aspx页面重定向到htm页面且http数据传输方式为“GET” if (rules[i].Type == WebType.Static && app.Context.Request.RequestType == "GET")
                        if (rules[i].Type == WebType.Static && app.Context.Request.RequestType == "GET") {
                        { //静态页面路径
                            //静态页面路径 string htmlWeb = RewriterUtils.ResolveUrl(httpContext.Request.ApplicationPath, rules[i].SendTo);
                            string htmlWeb = RewriterUtils.ResolveUrl(httpContext.Request.ApplicationPath, rules[i].SendTo); //静态页面的最后修改时间
                            //静态页面的最后修改时间 DateTime dt = System.IO.File.GetLastWriteTime(httpContext.Server.MapPath(htmlWeb));
                            DateTime dt = System.IO.File.GetLastWriteTime(httpContext.Server.MapPath(htmlWeb)); //当前时间和静态页面生成时间对比,如果时间小于一个小时,重定向到静态页面
                            //当前时间和静态页面生成时间对比,如果时间小于一个小时,重定向到静态页面 if (DateTime.Compare(DateTime.Now.AddHours(-1), dt) <= 0)
                            if (DateTime.Compare(DateTime.Now.AddHours(-1), dt) <= 0) {
                            { requestedPath = htmlWeb;
                                requestedPath = htmlWeb; }
                            } }
                        } else
                        else {
                        { requestedPath = rules[i].SendTo;
                            requestedPath = rules[i].SendTo; }
                        }
 // Rewrite the URL
                        // Rewrite the URL RewriterUtils.RewriteUrl(httpContext, requestedPath);
                        RewriterUtils.RewriteUrl(httpContext, requestedPath); break;        // exit the for loop
                        break;        // exit the for loop }
                    } }
                } }
            } }
        }
 }
    } }
}

 using System;
using System; using System.IO;
using System.IO; using System.Web.UI;
using System.Web.UI; using System.Web;
using System.Web; using URLRewriter.Config;
using URLRewriter.Config; using System.Configuration;
using System.Configuration; using System.Text.RegularExpressions;
using System.Text.RegularExpressions;
 namespace URLRewriter
namespace URLRewriter {
{ /// <summary>
    /// <summary> /// 依据web.config配置信息,生成静态页面
    /// 依据web.config配置信息,生成静态页面 /// </summary>
    /// </summary> public class CreateHtmFactoryHandler : IHttpHandlerFactory
    public class CreateHtmFactoryHandler : IHttpHandlerFactory {
    { /// <summary>
        /// <summary> ///
        ///  /// </summary>
        /// </summary> /// <param name="context">HttpContext 类的实例,它提供对用于为 HTTP 请求提供服务的内部服务器对象(如 Request、Response、Session 和 Server)的引用</param>
        /// <param name="context">HttpContext 类的实例,它提供对用于为 HTTP 请求提供服务的内部服务器对象(如 Request、Response、Session 和 Server)的引用</param> /// <param name="requestType">客户端使用的 HTTP 数据传输方法(GET 或 POST)</param>
        /// <param name="requestType">客户端使用的 HTTP 数据传输方法(GET 或 POST)</param> /// <param name="url">所请求资源的 RawUrl。</param>
        /// <param name="url">所请求资源的 RawUrl。</param> /// <param name="pathTranslated">所请求资源的 PhysicalApplicationPath</param>
        /// <param name="pathTranslated">所请求资源的 PhysicalApplicationPath</param> /// <returns>返回实现 IHttpHandler 接口的类的实例</returns>
        /// <returns>返回实现 IHttpHandler 接口的类的实例</returns> public virtual IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
        public virtual IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated) {
        { if (requestType == "GET")
            if (requestType == "GET") {
            { // get the configuration rules
                // get the configuration rules RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;
                RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;
 // iterate through each rule
                // iterate through each rule
 for (int i = 0; i < rules.Count; i++)
                for (int i = 0; i < rules.Count; i++) {
                { // get the pattern to look for, and Resolve the Url (convert ~ into the appropriate directory)
                    // get the pattern to look for, and Resolve the Url (convert ~ into the appropriate directory) string lookFor = "^" + RewriterUtils.ResolveUrl(context.Request.ApplicationPath, rules[i].LookFor) + "$";
                    string lookFor = "^" + RewriterUtils.ResolveUrl(context.Request.ApplicationPath, rules[i].LookFor) + "$";
 // Create a regex (note that IgnoreCase is set
                    // Create a regex (note that IgnoreCase is set )
) Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);
                    Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);
 // See if a match is found
                    // See if a match is found if (re.IsMatch(url) && rules[i].Type == WebType.Static)
                    if (re.IsMatch(url) && rules[i].Type == WebType.Static) {
                    { //得到要生成的静态页面的物理路径
                        //得到要生成的静态页面的物理路径 string physicsWeb = context.Server.MapPath(RewriterUtils.ResolveUrl(context.Request.ApplicationPath, rules[i].SendTo));
                        string physicsWeb = context.Server.MapPath(RewriterUtils.ResolveUrl(context.Request.ApplicationPath, rules[i].SendTo)); //设定Response筛选器
                        //设定Response筛选器 context.Response.Filter = new ResponseFilter(context.Response.Filter, physicsWeb);
                        context.Response.Filter = new ResponseFilter(context.Response.Filter, physicsWeb); break;
                        break; }
                    } }
                } }
            } //得到编译实例
            //得到编译实例 return PageParser.GetCompiledPageInstance(url, pathTranslated, context);
            return PageParser.GetCompiledPageInstance(url, pathTranslated, context); }
        }
 public virtual void ReleaseHandler(IHttpHandler handler)
        public virtual void ReleaseHandler(IHttpHandler handler) {
        { }
        } }
    } }
}
点击这里下载:源代码和示例
声明一下,我是在修改一个开源的项目(UrlRewrite)来实现上述功能。有关UrlRewrite介绍,请看这里,ASP.NET 中执行 URL 重写。
0 
0 
 
(请您对文章做出评价)
发表评论
不错! 
谢谢楼主!
谢谢楼主!
可以实现二级域名跳转吗?比如http://w12.abc.com/ -> http://www.abc.com/show.aspx?id=w12 
@ssssssssssssssss 
你修改一下(httpModules)源代码,应该是可以实现的。
你修改一下(httpModules)源代码,应该是可以实现的。
好像例子里没有调用的代码吧
友情提醒: 
return PageParser.GetCompiledPageInstance(url, pathTranslated, context);
PageParser.GetCompiledPageInstance 在.net2.0环境下 流量一大 cpu就100%, 此代码在cnblogs的源代码里也有。
所以还是慎重考虑。
需要用BuildManager类来替代
return PageParser.GetCompiledPageInstance(url, pathTranslated, context);
PageParser.GetCompiledPageInstance 在.net2.0环境下 流量一大 cpu就100%, 此代码在cnblogs的源代码里也有。
所以还是慎重考虑。
需要用BuildManager类来替代
2.0中不要使用PageParser.GetCompiledPageInstance
推荐使用BuildManager.CreateInstanceFromVirtualPath
see :
http://www.cnblogs.com/huobazi/archive/2007/12/31/UrlRewriteAndHttpHanderAndMakeStaticHtmlFiles.html
另外生成HTML这个工作放到HttpModule内比较好,否则启用HttpCompression的时候会有问题。 
微软好象有个开元的类是的东东
--引用-------------------------------------------------- 
殇: URLRewriter和生成静态页,我认为只要用一种方法就行了
--------------------------------------------------------
用静态页对服务器的压力比用"动态页"会小很多
殇: URLRewriter和生成静态页,我认为只要用一种方法就行了
--------------------------------------------------------
用静态页对服务器的压力比用"动态页"会小很多
CreateHtmFactoryHandler中的 
return PageParser.GetCompiledPageInstance(url, pathTranslated, context);
替换为
IHttpHandler handler = BuildManager.CreateInstanceFromVirtualPath(url, typeof(Page)) as IHttpHandler;
return handler;
return PageParser.GetCompiledPageInstance(url, pathTranslated, context);
替换为
IHttpHandler handler = BuildManager.CreateInstanceFromVirtualPath(url, typeof(Page)) as IHttpHandler;
return handler;
通过反射也可以实现 
CreateHtmFactoryHandler中的
return PageParser.GetCompiledPageInstance(url, pathTranslated, context);
替换为
PageHandlerFactory factory = (PageHandlerFactory)Activator.CreateInstance(typeof(PageHandlerFactory), true);
return factory.GetHandler(context, requestType, url, pathTranslated);
CreateHtmFactoryHandler中的
return PageParser.GetCompiledPageInstance(url, pathTranslated, context);
替换为
PageHandlerFactory factory = (PageHandlerFactory)Activator.CreateInstance(typeof(PageHandlerFactory), true);
return factory.GetHandler(context, requestType, url, pathTranslated);
在首页看到了 过来下栽 顺便帮你顶顶
谢谢正在找这个
好,非常有用,谢谢楼主
 
                    
                     
                    
                 
                    
                 
 
        
 
     
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号