生产环境NetFramework 3.0或3,5
以下我们定义一个HttpModule类继承IHttpModule接口
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Xml.Linq;
using System.Web;
/// <summary>
/// Summary description for HttpModule
/// </summary>
public class HttpModule:IHttpModule
{
private static Object obj = new object();
public void Init(HttpApplication app)
{
app.AuthenticateRequest += (object sender, EventArgs e) =>
{
HttpApplication app2 = (HttpApplication)sender;
Rewrite(app.Request.Path, app);
};
}
/// <summary>
/// URL 重写
/// </summary>
/// <param name="requestedPath"></param>
/// <param name="app"></param>
protected void Rewrite(string requestedPath, System.Web.HttpApplication app)
{
//从配置文件中读取要重写的路径
Dictionary<string, string> rules = new Dictionary<string, string>();
XDocument dom;
lock (obj)
{
dom = XDocument.Load(HttpContext.Current.Server.MapPath("/xml/Rewrite.config"));
}
var query = from r in dom.Descendants("rule")
select r;
foreach (var item in query)
{
rules.Add(item.Attribute("pattern").Value, item.Attribute("page").Value.Replace("^", "&"));
}
foreach (KeyValuePair<string, string> rule in rules)
{
Match match = Regex.Match(requestedPath, rule.Key, RegexOptions.IgnoreCase);
if (match.Success)
{
string sendToUrl = Regex.Replace(requestedPath, rule.Key, rule.Value, RegexOptions.IgnoreCase);
string path = sendToUrl;//虚拟路径
string querystring = string.Empty;//查询参数
if (sendToUrl.IndexOf("?") != -1)
{
path = sendToUrl.Substring(0, sendToUrl.IndexOf("?"));
querystring = sendToUrl.Substring(sendToUrl.IndexOf("?") + 1);
}
app.Context.RewritePath(path, string.Empty, querystring);
return;
}
}
}
public HttpModule()
{
}
///实现Dispose
public void Dispose()
{
}
}
下面是重写的配置文件
<?xml version="1.0" encoding="utf-8" ?>
<Rewrite>
<group comment="资讯栏目">
<rule pattern="(.*?)/news/(/w+)/-(/d+).aspx" page="/news.aspx/?t=$2^k=$3" comment="资讯最终页" />
</group>
<group comment="软件栏目">
<rule pattern="(.*?)/soft/(/w+)-(/d+)/.aspx" page="/soft.aspx/?t=$2^k=$3" comment="软件下载最终页" />
</group>
<group comment="音乐栏目">
<rule pattern="(.*?)/music/(/w+)-(/d+)/.aspx" page="/music.aspx/?t=$2^k=$3" comment="音乐最终页" />
</group>
</Rewrite>