文件: 404_Install.ashx
<%@ WebHandler Language="C#" Class="_404_Install" %>
using System;
using System.Web;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
public class _404_Install : IHttpHandler {
public struct URL
{
public string VisURL;
public string ToURL;
}
public void ProcessRequest (HttpContext context) {
// 映射关系 这里是静态页和动态页的关系
List<URL> WURL = new List<URL>();
WURL.Add(new URL{ VisURL = "/news/[a-z]+([0-9]+)[a-z]+([0-9]*).html" , ToURL="/news.aspx?id=$1&type=$2"});
WURL.Add(new URL{ VisURL = "/class/b([0-9]+)/([0-9]+)/*", ToURL="/class.aspx?id=$1&page=$2"});
WURL.Add(new URL{ VisURL = "/index.html", ToURL="/default.aspx"});
// 用户访问的URL http://www.baidu.com/123/123.htm
string Url = context.Request.Url.ToString().Split(';')[1];
// 获得域名 http://www.baidu.com
string Domain = "http://" + context.Request.Url.Host;
// 获得完整目录 /123/123.htm
// 可能是 /123/123 或 /123/123/ 此时需要加index.html
string FullPath = Url.ToLower().Replace("http://", "");
int Tmp = FullPath.IndexOf("/");
if (Tmp > -1)
FullPath = FullPath.Substring(Tmp, FullPath.Length - Tmp);
else
FullPath = "";
// 处理 /123/123/ -> /123/123
if (FullPath[FullPath.Length - 1] == '/')
FullPath = FullPath.Substring(0, FullPath.Length - 1);
// 判断是否是目录 目录则添加默认页
string[] AP = FullPath.Split('/');
if (AP[AP.Length-1].IndexOf('.') == -1)
FullPath = FullPath + "/index.html";
for (int i = 0; i < WURL.Count; i++)
{
if (Regex.IsMatch(FullPath, WURL[i].VisURL))
{
string DURL = Regex.Replace(Url, WURL[i].VisURL, WURL[i].ToURL);
if (SavePageAsFile(DURL, FullPath))
context.Response.Redirect(FullPath);
else
context.Response.Write("该页不存在!");
context.Response.End();
}
}
context.Response.Write("该页不存在!");
}
public bool SavePageAsFile(string url, string Path)
{
try
{
string result = "";
WebRequest wr = WebRequest.Create(url);
WebResponse wp = wr.GetResponse();
using (StreamReader sr = new StreamReader(wp.GetResponseStream(), Encoding.GetEncoding("gb2312")))
result = sr.ReadToEnd();
wp.Close();
// 为防止生成不存在的信息 可以在这一步对内容进行筛选
// 创建目录
string Dir = Path.Substring(0, Path.LastIndexOf('/'));
Dir = HttpContext.Current.Server.MapPath(Dir);
if (!Directory.Exists(Dir))
Directory.CreateDirectory(Dir);
// 创建文件
using (StreamWriter sw = new StreamWriter( HttpContext.Current.Server.MapPath(Path) , true, Encoding.GetEncoding("gb2312")))
sw.Write(result);
return true;
}
catch (Exception e)
{
//HttpContext.Current.Response.Write(e.Message);
return false;
}
}
public bool IsReusable {
get {
return false;
}
}
}
这是为 http://www.xiazais.com 和 http://mob.xiazais.com 提供的一种静态化方案的大致思路 由于站点原先是纯动态而且已经编译好了 并且源文件丢失 - -| 所以只得采用这种方法
修改好对应的URL关系后 将文件放在根目录下 然后设置IIS的404页为指定到URL 内容/404_Install.ashx 即可~