Go homepage(回首页)
Upload pictures (上传图片)
Write articles (发文字帖)

The author:(作者)归海一刀
published in(发表于) 2014/1/30 1:09:21
利用UrlRewrite,asp.net动态生成htm页面(补充说明2)_[Asp.Net教程]

利用UrlRewrite,asp.net动态生成htm页面(补充说明2)_[Asp.Net教程]

前几天写了两篇关于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
{
/**////


/// Provides a rewriting HttpModule.
///

public class ModuleRewriter : BaseModuleRewriter
{
/**////
/// This method is called during the module's BeginRequest event.
///

/// The RawUrl being requested (includes path and querystring).
/// The HttpApplication instance.
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







If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长)





QQ:154298438
QQ:417480759