1.首先在网站目录中建立URL重写规则的配置文件,这里存放在/Config/UrlRewrite.config文件中
<?xml version="1.0" encoding="utf-8"?>
<UrlRewriteConfig>
<Rules>
<RewriteRule>
<LookFor>/News</LookFor>
<SendTo>/News.aspx</SendTo>
</RewriteRule>
<RewriteRule>
<LookFor>/NewsInfo/(\d*)</LookFor>
<SendTo>/NewsInfo.aspx?id={0}</SendTo>
</RewriteRule>
<RewriteRule>
<LookFor>/Index</LookFor>
<SendTo>/Index.aspx</SendTo>
</RewriteRule>
</Rules>
</UrlRewriteConfig>2.建立Module类,这里命名为UrlRewriteModule,需要实现System.Web.IHttpModule接口
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml.Linq;
using BM.Framework;
namespace BigMiao
{
public class UrlRewriteModule : IHttpModule
{
public void Init(HttpApplication context)
{
//开始请求时,进入自定义的方法中过滤
context.BeginRequest += delegate (object sender, EventArgs args)
{
RewritePath(context);
};
}
/// <summary>
/// 重写URL
/// </summary>
/// <param name="context"></param>
private void RewritePath(HttpApplication context)
{
string requestFilePath = context.Request.Path;
//判断请求的路径,如果是JS,css,图片文件,则不重写
string exceptPath = requestFilePath.ToLower();
if (exceptPath.EndsWith(".js")
|| exceptPath.EndsWith(".css")
|| exceptPath.EndsWith(".png")
|| exceptPath.EndsWith(".jpg")
|| exceptPath.EndsWith(".gif"))
{
return;
}
//读取重写规则的配置文件,频繁读取使用缓存
string configDir = context.Server.MapPath("~/Config/UrlRewrite.config");
var xdoc = (CacheUtil.Instance.GetCache("UrlRewriteConfig") as XDocument)
?? XDocument.Load(configDir);
var rules = from rule in xdoc.Descendants("RewriteRule")
select new
{
LookFor = rule.Element("LookFor")?.Value,
SendTo = rule.Element("SendTo")?.Value
};
foreach (var rule in rules)
{
//使用正则匹配重写规则
var regex = new Regex("^" + rule.LookFor + "$", RegexOptions.IgnoreCase);
var match = regex.Match(requestFilePath);
if (match.Success)
{
var listKey = new List<string>();
for (var i = 0; i < match.Groups.Count; i++)
{
if (i > 0)
listKey.Add(match.Groups[i].Value);
}
string realUrl = rule.SendTo.FormatWith(listKey.ToArray());//这里是对string类型的扩展,类同于String.Format("xxxx{0}xxxx", "OOOO")
context.Context.RewritePath(realUrl);//重写至真实路径
break;
}
}
}
//实现IHttpModule必备方法
public void Dispose()
{
}
}
}3.在web.config中配置HttpModule
应用程序池经典模式,在<system.web>节点内配置:
<httpModules> <!--Url重写--> <add name="UrlRewriteModule" type="BigMiao.UrlRewriteModule" /> </httpModules>
应用程序池集成模式,在<system.webServer>节点内配置:
<modules> <!--Url重写--> <add name="UrlRewriteModule" type="BigMiao.UrlRewriteModule" /> </modules>
OK,大功告成!