asp.net的rul重寫
有關于url的重寫,本文也只是拿來主意。相繼有ms的組件“urlrewriter”和在global.asax里的“application_beginrequest()”編碼方式,以及iis里的isapi設置。
娜列下來,實現方法也都很簡單。
方法一:ms組件
這里也不用詳解了,相關請看:
http://www.microsoft.com/china/msdn/library/webservices/asp.net/urlrewriting.mspx
用法很簡單,只需要把組件urlrewriter.dll拷到應用程序的bin目錄下,然后在web.config下加入如下代碼:
在<configuration></configuration>中加入:
<configsections>
<section name="rewriterconfig" type="urlrewriter.config.rewriterconfigserializersectionhandler, urlrewriter" />
</configsections>
<rewriterconfig>
<rules>
<rewriterrule>
<lookfor>~/(/d{4})/(/d{2})/default/.aspx</lookfor>
<sendto>~/default.aspx?id=$1</sendto>
</rewriterrule>
</rules>
</rewriterconfig>
然后在<system.web></system.web>中加入:
<httphandlers>
<add verb="*" path="*.aspx"
type="urlrewriter.rewriterfactoryhandler, urlrewriter" />
</httphandlers>
最后在地址欄上鍵入:http://localhost/test/2004/12/news.aspx
效果出來了。
上面的<lookfor>~/(/d{4})/(/d{2})/news/.aspx</lookfor>這句這正則表達式url,即被重寫的url,而<sendto>~/default.aspx?id=$1</sendto>這一句為原始url地址。其中的$1為第一個正則表達式值(上面例子為:2004),以此類推,第二個即為$2
方法二:application_beginrequest()
在應用程序中新建一個xml文件,文件內容為:文件名rewriter.config
<?xml version="1.0" encoding="utf-8" ?>
<rewriterurls>
<rule>
<old>(.*)/news/(/d{4})/default/.aspx</old>
<new>../../default.aspx?id=$2&type=$3</new>
</rule>
</rewriterurls>
在global.asax文件中的application_beginrequest(object sender, eventargs e)加入代碼:
try
{
string path=server.mappath("~/rewriter.config");
xpathdo***ent myxpathdo***ent = new xpathdo***ent(path);
xpathnavigator myxpathnavigator = myxpathdo***ent.createnavigator();
xpathnodeiterator myxpathnodeiterator = myxpathnavigator.select ("http://rule");
system.text.regularexpressions.regex oreg;
string rewriteurl;
while (myxpathnodeiterator.movenext())
{
//oreg=new regex(onode.selectsinglenode("url/text()").value);
xpathnavigator nav2 = myxpathnodeiterator.current.clone();
string oldstring="",newstring="";
xpathnodeiterator it2 = nav2.select("old");
while(it2.movenext())
{
oldstring = it2.current.value;
break
}
it2 = nav2.select("new");
while(it2.movenext())
{
newstring = it2.current.value;
break
}
if(oldstring != "" && newstring != "")
{
oreg = new system.text.regularexpressions.regex(oldstring);
if(oreg.ismatch(request.url.tostring()))
{
rewriteurl = oreg.replace(request.url.tostring(),newstring);
httpcontext.current.rewritepath(rewriteurl);
break
}
}
}
}
catch
{
}
新聞熱點
疑難解答
圖片精選