最近在做政府门户时用最简单的方法实现了对url的改写成html格式,下面我把代码贴出来,供参考.
using System;
using System.Web;
using System.Web.Caching;
using System.Web.Security;
using System.Text.RegularExpressions;
using System.Web.SessionState;
namespace DXWeb
{
/// <summary>
/// URL 重写
/// </summary>
public class UrlReWrite : IHttpHandler ,IRequiresSessionState
{
/// <summary>
/// 通过实现 IHttpHandler 接口的自定义 HttpHandler 启用 HTTP Web 请求的处理。
/// </summary>
/// <param name="context">HttpContext 对象,它提供对用于为 HTTP 请求提供服务的内部服务器对象(如 Request、Response、Session 和 Server)的引用。 </param>
public void ProcessRequest(HttpContext Context)
{
try
{
int type = 0;
string Url = Context.Request.Url.AbsolutePath;
Url = Url.Substring(Url.LastIndexOf("/") + 1,Url.Length - Url.LastIndexOf("/") - 1);
Url = Url.Substring(0,Url.IndexOf(".")).ToLower();
//如果第1位是f则指明是栏目页
if (Url.Substring(0,1) == "f")
{
Url = Url.Substring(1,Url.Length - 1);
type = 1;
}
else if (Url.Substring(0,1) == "n")//新闻
{
Url = Url.Substring(1,Url.Length - 1);
type = 2;
}
else if (Url.Substring(0,1) == "v")//视频
{
Url = Url.Substring(1,Url.Length - 1);
type = 3;
}
else if (Url.Substring(0,1) == "s")//网上办事
{
Url = Url.Substring(1,Url.Length - 1);
type = 4;
}
else if (Url.Substring(0,1) == "z")//办事指南
{
Url = Url.Substring(1,Url.Length - 1);
type = 5;
}
//检查文件名是否数字
if (Common.CheckInput(Url,"^[1-9][0-9]{0,9}$"))
{
foreach (string key in Context.Request.QueryString.AllKeys)
Url += "&" + key + "=" + Context.Request.QueryString[key];
if (type == 1)
Context.Server.Execute("Navigate.aspx?id=" + Url);
else if (type == 2)
Context.Server.Execute("News.aspx?id=" + Url);
else if (type == 3)
Context.Server.Execute("ShowVideo.aspx?id=" + Url);
else if (type == 4)
Context.Server.Execute("Service.aspx?id=" + Url);
else if (type == 5)
Context.Server.Execute("ShowService.aspx?id=" + Url);
}
else
{
//否则查看硬盘是否有此文件
}
}
catch// (Exception ex)
{
//Context.Response.Write(ex.Message);
}
}
/// <summary>
/// 获取一个值,该值指示其他请求是否可以使用 IHttpHandler 实例。
/// </summary>
public bool IsReusable
{
get
{
return false;
}
}
}
}
大概思路是调用IHttpHandler接口将原来的ulr输入缓存l转换成html格式后输出,当然需要iis支持.