以前用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中,至于如何實現轉換見下一頁。
最大的網站源碼資源下載站,
新聞熱點
疑難解答