作者的blog:www.lemongtree.com
以前用url重写时是用的ms urlrewriter,用了以后发现了很多不足,自定义功能太弱,而且随着重写规则的增加,web.config可能会越来越大,实际上,url重写就是实现ihttphandler接口.
整个流程分二步走:
1、用一个xml文件来存储重写规则,其中这些规则是一些简单的正则表达式
2、实现ihttphandler接口
首先看一下xml文件的格式:
<?xml version="1.0" encoding="utf-8" ?>
<root>
<regex>
<!--重写以后的虚拟地址-->
<b><![cdata[xxx,(?<id>[0-9]+).html$]]></b>
<!--实际地址-->
<a><![cdata[xxx.aspx?id=${id}]]></a>
</regex>
</root>
相信上面的xml大家都能看懂.
using system;
using system.io;
using system.data;
using system.configuration;
using system.collections.generic;
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;
using system.text;
using system.text.regularexpressions;
using microsoft.visualbasic;
//regexinfo结构,用来存储从xml文件中读取到的数据
public struct regexinfo
{
public string _before;
public string _after;
public regexinfo(string before, string after)
{
_before = before.tolower();
_after = after.tolower();
}
}
//ipfilter结构,用来存储被封的ip
public struct ipfilter
{
public string _ip;
public ipfilter(string ip)
{
_ip = ip;
}
}
public class htmlhttphandler : ihttphandler //实现ihttphandler接口
{
private list<regexinfo> _regex_list = new list<regexinfo>();
private list<ipfilter> _ip_filter = new list<ipfilter>();
public htmlhttphandler()
{
dataset ds = new dataset();
//读取url重写规则文件,并写入regexinfo结构的实例中
ds.readxml(system.web.httpcontext.current.server.mappath("~/app_data/regexs.xml"));
foreach (datarow r in ds.tables["regex"].rows)
_regex_list.add(new regexinfo(((string)r["b"]).trim(), ((string)r["a"]).trim()));
ds.reset();
//读取被封的ip列表
ds.readxml(system.web.httpcontext.current.server.mappath("~/app_data/ipfilter.xml"));
foreach(datarow r in ds.tables["ipfilters"].rows)
_ip_filter.add(new ipfilter((string)r["ip"]));
}
public void processrequest(httpcontext context)
{
string _ip = context.request.userhostaddress; //获取ip
foreach (ipfilter r in _ip_filter)
{
if (_ip == r._ip)
{
context.response.write("对不起,您的ip:"+_ip+"已被限制!");
context.response.end();
}
}
string path = context.request.path.tolower(); //获取当前访问的重写过的虚假url
foreach (regexinfo r in _regex_list)
path = regex.replace(path, r._before, r._after); //匹配出其真实的url
context.server.execute(path);
}
// override the isreusable property.
public bool isreusable
{
get { return true; }
}
}
ok,ihttphandler接口就被实现了,下面稍配一下web.config就可以实现url重写了
在web.config的<system.web></system.web>中加入 :
<httphandlers>
<add verb="*" path="*.html" type="htmlhttphandler"/>
</httphandlers>
表示后缀名为.html的文件全部交给htmlhttphandler类去处理
最后配一下iis就行了。
至于简繁的转换,你可以加到processrequest中,至于如何实现转换见下一页。
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器