当前位置:首页 > 网络编程 > 软件语言 > .NET > 利用UrlRewrite,asp.net动态生成htm页面

利用UrlRewrite,asp.net动态生成htm页面

点击次数:52 次 发布日期:2008-11-06 08:09:12 作者:源代码网
源代码网推荐
广告载入中

源代码网整理以下在web.config中进行简单配置,就可以达到动态生成静态页面的效果,同时又不影响Url重定向。web.config中需要注意的配置节为<configuration>、<RewriteConfig>、<httpModules>、<httpHandlers>,在这些配置节里边都有注释,容易看懂。
<?xml version="1.0" encoding="utf-8"?>
<!--
    注意: 除了手动编辑此文件以外,您还可以使用
    Web 管理工具来配置应用程序的设置。可以使用 Visual Studio 中的
     “网站”->“Asp.Net 配置”选项。
    设置和注释的完整列表在
    machine.config.comments 中,该文件通常位于
    WindowsMicrosoft.NetFrameworkv2.xConfig 中
-->
<configuration>

源代码网整理以下  <!-- RUL重写开始 -->
  <configSections>
    <section name="RewriterConfig" type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter"/>
  </configSections>
  <RewriterConfig>
    <Rules>
      <!--地址重写规则-->
      <!--首页,定位到静态页面-->
      <RewriterRule>
        <Type>Static</Type>
        <LookFor>~/Default.aspx</LookFor>
        <SendTo>~/Default.htm</SendTo>
      </RewriterRule>
      <!--二级页面,定位到动态页面-->
      <RewriterRule>
        <Type>Dynamic</Type>


        <LookFor>~/List.aspx</LookFor>
        <SendTo>~/Show.aspx</SendTo>
      </RewriterRule>
    </Rules>
  </RewriterConfig>
  <!-- RUL重写结束 -->

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

源代码网整理以下        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->
    <globalization requestEncoding="utf-8" responseEncoding="utf-8"/>
  </system.web>
</configuration>
两个关键的类是ModuleRewriter和RewriterFactoryHandler
ModuleRewriter类用于Url重定向,代码如下:
ModuleRewriter
using System;
using System.Text.RegularExpressions;
using System.Configuration;
using URLRewriter.Config;
using System.Data;

软件开发网 www.mscto.com

using System.Web;
using System.Web.UI;

源代码网整理以下namespace URLRewriter
{
    /**//// <summary>
    /// Provides a rewriting HttpModule.
    /// </summary>
    public class ModuleRewriter : BaseModuleRewriter
    {
        /**//// <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)
        {


            //只对文件后缀为aspx页面有效
            if (requestedPath.IndexOf(".aspx") != -1)
            {
                HttpContext httpContext = app.Context;

源代码网整理以下                // 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(httpContext.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))
                    {
                        //aspx页面重定向到htm页面且http数据传输方式为“GET”
                        if (rules[i].Type == WebType.Static && app.Context.Request.RequestType == "GET")
                        {
                            //静态页面路径
                            string htmlWeb = RewriterUtils.ResolveUrl(httpContext.Request.ApplicationPath, rules[i].SendTo);
                            //静态页面的最后修改时间
                            DateTime dt = System.IO.File.GetLastWriteTime(httpContext.Server.MapPath(htmlWeb));
                            //当前时间和静态页面生成时间对比,如果时间小于一个小时,重定向到静态页面
                            if (DateTime.Compare(DateTime.Now.AddHours(-1), dt) <= 0)


                            {
                                requestedPath = htmlWeb;
                            }
                        }
                        else
                        {
                            requestedPath = rules[i].SendTo;


                        }

源代码网整理以下                        // Rewrite the URL
                        RewriterUtils.RewriteUrl(httpContext, requestedPath);
                        break;        // exit the for loop
                    }
                }
            }
        }

源代码网整理以下    }
}
CreateHtmFactoryHandler类用于生成静态页面,代码如下:
CreateHtmFactoryHandler
using System;
using System.IO;
using System.Web.UI;
using System.Web;
using URLRewriter.Config;
using System.Configuration;
using System.Text.RegularExpressions;

源代码网整理以下namespace URLRewriter
{
    /**//// <summary>
    /// 依据web.config配置信息,生成静态页面
    /// </summary>
    public class CreateHtmFactoryHandler : IHttpHandlerFactory
    {
        /**//// <summary>
        ///
        /// </summary>
        /// <param name="context">HttpContext 类的实例,它提供对用于为 HTTP 请求提供服务的内部服务器对象(如 Request、Response、Session 和 Server)的引用</param>
        /// <param name="requestType">客户端使用的 HTTP 数据传输方法(GET 或 POST)</param>
        /// <param name="url">所请求资源的 RawUrl。</param>
        /// <param name="pathTranslated">所请求资源的 PhysicalApplicationPath</param>
        /// <returns>返回实现 IHttpHandler 接口的类的实例</returns>
        public virtual IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
        {
            if (requestType == "GET")
            {
                // 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(context.Request.ApplicationPath, rules[i].LookFor) + "$";

源代码网整理以下                    // Create a regex (note that IgnoreCase is set)
                    Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);

软件开发网 www.mscto.com

源代码网整理以下                    // See if a match is found
                    if (re.IsMatch(url) && rules[i].Type == WebType.Static)
                    {
                        //得到要生成的静态页面的物理路径
                        string physicsWeb = context.Server.MapPath(RewriterUtils.ResolveUrl(context.Request.ApplicationPath, rules[i].SendTo));
                        //设定Response筛选器


                        context.Response.Filter = new ResponseFilter(context.Response.Filter, physicsWeb);
                        break;
                    }
                }
            }
            //得到编译实例
            return PageParser.GetCompiledPageInstance(url, pathTranslated, context);
        }

源代码网整理以下        public virtual void ReleaseHandler(IHttpHandler handler)
        {
        }
    }
}
以上是两个主要的类,还有一些辅助的类,我把测试项目附上,里边有源代码和示例。
点击这里下载:

/upimg/soft/1_080131124917.rar


源代码网推荐

源代码网供稿.
网友评论 (0)
会员中心
网络编程
本站推荐
网络编程之精华