其实这是利用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>节点下添加如下代码:
- <httpHandlers>
- <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:
- <httpHandlers>
- <add verb="*" path="*/show-?*-?*.html" type="UrlRewriter" />
- </httpHandlers>
现在打开网站输入地址http://localhost:80/show-12-34.html 访问一下~!
方法二:地址重写、使用伪静态、页面回发处理
制作网站页面的时候,有时候为了用户的体验和搜索引擎的收录,很多网站经常使用伪静态地址重写,或者称为 URL地址重写的办法,来将诸如:MyEbook.aspx?ID=1,MyEbook.aspx?ID=2MyEbook.aspx?ID=3等带有参 数的动态页面伪装成为一个静态页面,比如,将以上的伪装成为My1.html,My2.html,My3.html等等诸如此类!
出发点是很好的,不仅有利于用户体验,也有利于收录,实在是一举两得!
好处已讲,现在来谈谈使用这种办法所存在的毛病,问题就在于,当你使用伪静态技术的页面有按钮,需要提交内容时,这个时候,一旦与服务器之间有回发动作, 那么,地址栏里面显示的网页地址就不再是伪装出来的My1.html,My2.html,My3.html等等拉,而是变为MyEbook.aspx? ID=1,MyEbook.aspx?ID=2MyEbook.aspx?ID=3等等洛,如此一来,会让不太懂网页制作的网友感到不安,他们会认为自己 在上一个骗子网站,认为自己提交的数据都被另外一个网站给偷走了,总之,给他们的感觉就是,这样的网站具有欺骗性质;很可能,以后他们再也不敢上你的网站 了!!!………