62,046
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
namespace Code.Web.HttpModule
{
public class URLRewriter : IHttpModule
{
#region IHttpModule 成员
public void Dispose()
{
throw new Exception("The method or operation is not implemented.");
}
public void Init(HttpApplication context)
{
try
{
// 取得原始URL屏蔽掉参数
string Url = context.Request.RawUrl;
// 建立正则表达式
Regex Reg = new Regex(@"/show-(\d+)-(\d+)\..+", RegexOptions.IgnoreCase);
// 用正则表达式进行匹配
Match m = Reg.Match(Url, Url.LastIndexOf("/"));
// 从最后一个“/”开始匹配
if (m.Success)
// 重写路径
context.RewritePath(@"~/aspx/show.aspx?type=" + m.Groups[1] + "&id=" + m.Groups[2]);
else
context.Response.Redirect(context.Request.Url.ToString());
}
catch
{
context.Response.Redirect(context.Request.Url.ToString());
}
}
#endregion
}
}
<configSections>
<section name="RewriterConfig" type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter" />
</configSections>
<httpModules>
<add type="URLRewriter.ModuleRewriter, URLRewriter" name="ModuleRewriter" />
</httpModules>
<!-- 下面是配置重写URL规则 -->
<RewriterConfig>
<Rules>
<RewriterRule>
<LookFor>~/Products/Jurisdiction_(\w{3})\.aspx</LookFor>
<SendTo>~/En/Jurisdiction.aspx?jurid=$1</SendTo>
</RewriterRule>
<RewriterRule>
<LookFor>~/Articles/(\d{1,})\.aspx</LookFor> <!-- 这个是被代替后的文件名,使用到正则表达式 -->
<SendTo><![CDATA[~/En/Article_view.aspx?article_id=$1]]></SendTo> <!-- 这个是要给代替的网页,一般是带有问号后面带参数的网页 -->
</RewriterRule>
<RewriterRule>
<LookFor>~/Articles/(\d{1,})_(\d{1,})\.aspx</LookFor>
<SendTo><![CDATA[~/En/Article_view.aspx?article_id=$1&page=$2]]></SendTo>
</RewriterRule>
</Rules>
</RewriterConfig>