asp.net
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>這句這RegexURL,即被重寫的URL,而<SendTo>~/Default.aspx?ID=$1</SendTo>這一句為原始URL地址。其中的$1為第一個Regex值(上面例子為: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 ("//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
{
}