





















namespace JC.Web
{
/// <summary>
/// URLRewriter 的摘要说明。
/// </summary>
public class Rewriter : IConfigurationSectionHandler
{
protected XmlNode _oRules=null;
protected Rewriter(){}
public string GetSubstitution(string zPath)
{
Regex oReg;
foreach(XmlNode oNode in _oRules.SelectNodes("rule"))
{
oReg=new Regex(oNode.SelectSingleNode("url/text()").Value);
Match oMatch=oReg.Match(zPath);
if(oMatch.Success)
{
return oReg.Replace(zPath,oNode.SelectSingleNode("rewrite/text()").Value);
}
}
return zPath;
}
public static void Process()
{
Rewriter oRewriter=(Rewriter)ConfigurationSettings.GetConfig("system.web/urlrewrites");
string zSubst=oRewriter.GetSubstitution(HttpContext.Current.Request.Path.ToLower());
if(zSubst.Length>0)
{
HttpContext.Current.RewritePath(zSubst);
}
}
#region Implementation of IConfigurationSectionHandler
public object Create(object parent, object configContext, XmlNode section)
{
_oRules=section;
// TODO: Compile all Regular Expressions
return this;
}
#endregion
}
}
Web.Config
<urlrewrites>
<rule>
<url>/default.html</url>
<rewrite>/default.aspx</rewrite>
</rule>
<rule>
<url>/products.html</url>
<rewrite>products/products.aspx</rewrite>
</rule>
<rule>
<url>/axblog.html</url>
<rewrite>blog/blog.aspx?cid=2</rewrite>
</rule>
<rule>
<url>/blog/a(\d+).html</url>
<rewrite>/blog/blogdetail.aspx?aid=$1</rewrite>
</rule>
<rule>
<url>/blog/cid(\d+).html</url>
<rewrite>/blog/blog.aspx?cid=$1</rewrite>
</rule>
<rule>
<url>/blog/c(\d+)a(\d+).html</url>
<rewrite>/blog/blogdetail.aspx?cid=$1&aid=$2</rewrite>
</rule>
<rule>
<url>/blog/dt(\d+).html</url>
<rewrite>/blog/blog.aspx?dt=$1</rewrite>
</rule>
<rule>
<url>/support/faq_cid(\d+).html</url>
<rewrite>/support/faqlist.aspx?cid=$1</rewrite>
</rule>
<rule>
<url>/support/faq_c(\d+)a(\d+).html</url>
<rewrite>/support/faqdetail.aspx?cid=$1&aid=$2</rewrite>
</rule>
<rule>
<url>(.+)\.html</url>
<rewrite>$1.aspx</rewrite>
</rule>
</urlrewrites>
Global
protected void Application_BeginRequest(Object sender, EventArgs e)
{
JC.Web.Rewriter.Process();
}
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。