利用UrlRewrite,asp.net动态生成htm页面(补充说明2)

来源:互联网 发布:mssql注入语句 编辑:程序博客网 时间:2024/05/18 22:09

前几天写了两篇关于URL重写时,生成静态页面的随笔。

利用UrlRewrite,asp.net动态生成htm页面
利用UrlRewrite,asp.net动态生成htm页面(补充说明)
今天把原来的思路给整理了一下,原来需要两个类(ModuleRewriter和CreateHtmFactoryHandler)才能完成整个过程,现在只用ModuleRewriter就可以了,我画了个流程图


关键类ModuleRewriter代码

Code
using System;
using System.Text.RegularExpressions;
using System.Configuration;
using URLRewriter.Config;
using System.Data;
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);
//静态页面物理路径
string htmPath = httpContext.Server.MapPath(htmlWeb);
//静态页面的最后修改时间
DateTime dt = System.IO.File.GetLastWriteTime(htmPath);
if (DateTime.Compare(DateTime.Now.AddHours(-1), dt) <= 0) //当前时间和静态页面生成时间对比,如果时间小于一个小时,重定向到静态页面
{
requestedPath = htmlWeb;
}
else //当前时间和静态页面生成时间对比,如果时间大于一个小时,设定Response筛选器,用于生成静态页面
{
httpContext.Response.Filter = new ResponseFilter(httpContext.Response.Filter, htmPath);
}
}
else
{
requestedPath = rules[i].SendTo;
}

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

}
}

原代码和演示示例 下载

来源:http://www.cnblogs.com/fengfeng