ASP.NET2.0利用httphandler实现URL重写(伪URL及伪静态)
ASP.NET2.0利用httphandler实现URL重写(伪URL及伪静态)
网站技术 2007-10-25 23:07:31 阅读56 评论0 字号:大中小 订阅
我们有时候会见到这样的地址:“http://www.huoho.com/show-12-34.html”,你或许认为在站点服务器根目录“/”下存在名为“show-12-34.html”的文件,其实实际它可能是不存在的,而可能你看到的内容是“/aspx/show.aspx?type=12&id=34”的内容,为什么要这样做呢?原因有多个方面:首先是增强URL的友好性,记“show-12-34.html”总比“/aspx/show.aspx?type=12&id=34”好记吧?其次就是方便搜索引擎收录,很多搜索引擎更看好静态HTML页,比如:百度;其次就是出于安全性的考虑,因为这样隐藏了参数“type”、“id”。是不是很有意思呢?
其实这是利用URL重写实现的,下面我就说一下在ASP.NET2.0下我所知道的最简单的实现方法:通过实现接口“IHttpHandler”来接管HTTP请求,Follow me!
1.在资源管理方案中添加一个类,类的代码如下:
//类URLRewriter程序清单:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
/// <summary>
/// UrlRewriter URL重写类
/// Author:yoyo
/// blog:http://yangmingsheng.cn
/// </summary>
public class UrlRewriter : IHttpHandler //实现“IHttpHandler”接口
{
public UrlRewriter()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public void ProcessRequest(HttpContext Context)
{
try
{
//取得原始URL屏蔽掉参数
string Url = Context.Request.RawUrl;
//建立正则表达式
System.Text.RegularExpressions.Regex Reg = new System.Text.RegularExpressions.Regex(@"/show-(\d+)-(\d+)\..+",System.Text.RegularExpressions.RegexOptions.IgnoreCase);
//用正则表达式进行匹配
System.Text.RegularExpressions.Match m = Reg.Match(Url,Url.LastIndexOf("/"));//从最后一个“/”开始匹配
if (m.Success)//匹配成功
{
String RealPath = @"~/aspx/show.aspx?type=" + m.Groups[1] + "&id=" + m.Groups[2];
//Context.Response.Write(RealPath);
//Context.RewritePath(RealPath);//(RewritePath 用在无 Cookie 会话状态中。)
Context.Server.Execute(RealPath);
}
else {
Context.Response.Redirect(Context.Request.Url.ToString());
}
}
catch
{
Context.Response.Redirect(Context.Request.Url.ToString());
}
}
/// <summary>
/// 实现“IHttpHandler”接口所必须的成员
/// </summary>
/// <value></value>
/// Author:yoyo
/// blog:http://yangmingsheng.cn
public bool IsReusable
{
get { return false; }
}
}
2.在web.config文件还要添加一下设置项
在<system.web>节点下添加如下代码:
<add verb="*" path="*/show-?*-?*.aspx" type="UrlRewriter" />
</httpHandlers>
解释一下:
verb是指允许的动作“GET”、“POST”、“PUT”中的一种或几种,星号“*”表示全部允许;
path是指匹配路径,支持简单的通配符;
type是指绑定的类名以及包括命名空间(如果有的话);
对了,首先你要建立一个WEB窗体“show.aspx”在目录“aspx”下,因为这个文件就是实际接受请求并显示相关内容的页面。
OK!,编译,打开网站输入地址http://localhost:80/show-12-34.aspx 访问一下,检查看是不是显示的“/aspx/show.aspx?type=12&id=34”的内容呢?!
上面我是设置了匹配ASPX文件,因为IIS里.HTML扩展名默认是不归ASP.NET接管的,如果要接管HTML请求,请将IIS的扩展名.HTML映射到“C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll”,然后将上面的aspx改成html:
<add verb="*" path="*/show-?*-?*.html" type="UrlRewriter" />
</httpHandlers>
现在打开网站输入地址http://localhost:80/show-12-34.html 访问一下~!
OVER,好累呀,需要转载的注意记得把来源写清,我写了那么多也不容易,=_=(http://yangmingsheng.cn,作者:YoYo)。
2007/08/28 更新:
看到还有人关注,我就把后来修改的都写出来,要完整的项目代码,请给我发邮件:mini125#gmail.com (#改@),只是想统计一下到底有没有人在用~
修改后的代码更通用化,你只需在URLRewriterSettings.xml指定重写规则就行了:
1.文件UrlRewriter.cs代码:(放于App_Code/下)
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
/// <summary>
/// UrlRewriter URL重写类
/// Author:yoyo
/// blog:http://yangmingsheng.cn
/// </summary>
public class UrlRewriter : IHttpHandler
{
public UrlRewriter()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public void ProcessRequest(HttpContext Context)
{
//取得原始URL屏蔽掉参数
string Url = Context.Request.RawUrl;
System.Xml.XmlDocument Dom = new System.Xml.XmlDocument();
Dom.Load(HttpContext.Current.Server.MapPath(ConfigurationSettings.AppSettings["urlRewriter"]));//从web.config读取设置文件URLRewriterSettings.xml的路径
System.Xml.XmlNodeList ItemList = Dom.SelectSingleNode(@"//URLRewriters").ChildNodes;
foreach (System.Xml.XmlNode Node in ItemList)
{
//if(!Node.HasChildNodes) continue;
String Ph = Node.Attributes.GetNamedItem(@"Path").InnerText;
String Rh = Node.Attributes.GetNamedItem(@"RealPath").InnerText;
if (Ph.StartsWith(@"~")) Ph = HttpContext.Current.Request.ApplicationPath + Ph.Substring(1);
if (Rh.StartsWith(@"~")) Rh = HttpContext.Current.Request.ApplicationPath + Rh.Substring(1);
//建立正则表达式
System.Text.RegularExpressions.Regex Reg = new System.Text.RegularExpressions.Regex(Ph, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Match m = Reg.Match(Url);//匹配
if (m.Success)//成功
{
for (int i = 1; i <= m.Groups.Count; i++)
{
Rh = Rh.Replace("$" + i.ToString(), m.Groups[i].Value);
}
//Context.Response.Write(Context.Request.Url.PathAndQuery);
//Context.RewritePath(RealPath);//(RewritePath 用在无 Cookie 会话状态中。)
Context.Server.Execute(Rh);
Context.Response.End();
break;
}
}
try
{
Context.Server.Execute(Context.Request.Url.PathAndQuery);
}
catch
{
Context.Response.Write("404 ERROR!");
Context.Response.End();
}
}
/// <summary>
/// 实现“IHttpHandler”接口所必须的成员
/// </summary>
/// <value></value>
/// Author:yoyo
/// blog:http://yangmingsheng.cn
public bool IsReusable
{
get { return false; }
}
}
2.web.config代码:
<?xml version="1.0"?>
<!--
注意: 除了手动编辑此文件以外,您还可以使用
Web 管理工具来配置应用程序的设置。可以使用 Visual Studio 中的
“网站”->“Asp.Net 配置”选项。
设置和注释的完整列表在
machine.config.comments 中,该文件通常位于
\Windows\Microsoft.Net\Framework\v2.x\Config 中
-->
<configuration>
<appSettings>
<add key="urlRewriter" value="~/App_Data/URLRewriterSettings.xml"/><!--配置文件路径-->
</appSettings>
<connectionStrings/>
<system.web>
<httpHandlers>
<add verb="*" path="?*.html" type="UrlRewriter" /><!--加载重写类,并利用通配符粗略指定规则-->
</httpHandlers>
<!--
设置 compilation debug="true" 将调试符号插入
已编译的页面中。但由于这会
影响性能,因此只在开发过程中将此值
设置为 true。
-->
<compilation debug="true"/>
<!--
通过 <authentication> 节可以配置 ASP.NET 使用的
安全身份验证模式,
以标识传入的用户。
-->
<authentication mode="Windows"/>
<!--
如果在执行请求的过程中出现未处理的错误,
则通过 <customErrors> 节可以配置相应的处理步骤。具体说来,
开发人员通过该节可以配置
要显示的 html 错误页
以代替错误堆栈跟踪。
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
</system.web>
</configuration>
3. URLRewriterSettings.xml(配置文件)代码(此例将其放在App_Data/目录下):
<?xml version="1.0" encoding="utf-8" ?>
<!--如有多个匹配,则优先级向下递减-->
<!--http://localhost:6679/httphandleUrlRewrite/22.html-->
<!--http://localhost:6679/httphandleUrlRewrite/a/b/c.html-->
<!--如有多个匹配,则优先级向下递减-->
<URLRewriters>
<URLRewriters Path=".+?/(\d+).html" RealPath="~/aspx/show.aspx?id=$1" />
<URLRewriters Path="~/([^/]*)/([^/]*)/([^/]*).html" RealPath="~/aspx/show.aspx?par1=$1&par2=$2&par3=$3"/>
</URLRewriters>
需要完整项目测试代码,可发邮件索取:mini125#gmail.com (#改@),只是想统计一下到底有没有人在用~