- 方法一: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 type="URLRewriter.RewriterFactoryHandler, URLRewriter" path="*.aspx" verb="*" />
- </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");
- XPathDocument myXPathDocument = new XPathDocument(path);
- XPathNavigator myXPathNavigator = myXPathDocument.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{ }
- 最后在地址栏上键入:http://localhost/Test/News/2004/Default.aspx
- 效果出来了。
asp.net的url重写
最新推荐文章于 2024-11-07 09:39:08 发布