原理: HttpModule模块在任何请求发生时都会执行,所有可以在该类中执行Url的重映射跳转
第一步:定义IHttpModule
public class UrlRemapper : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
HttpContext context = app.Context;
//获取当前请求页面
string currentUrl = context.Request.AppRelativeCurrentExecutionFilePath;
//获取包含映射关系的xml文件
XmlDocument doc = GetUrlMapperings(context);
XmlNodeList nodes = doc.SelectNodes("//add");
foreach (XmlNode item in nodes)
{
string url = item.Attributes["url"].Value;
string mapperUrl = item.Attributes["mappedUrl"].Value;
if (Regex.Match(currentUrl, url, RegexOptions.IgnoreCase).Success)
{
//如果请求页面包含在映射关系内,则跳转页面
context.RewritePath(mapperUrl);
}
}
}
private XmlDocument GetUrlMapperings(HttpContext context)
{
XmlDocument doc = new XmlDocument();
doc.Load(context.Server.MapPath("~/UrlMappings.xml"));
return doc;
}
public void Dispose()
{
//throw new NotImplementedException();
}
}
第二步:在Web.config中注册IHttpModule
<system.web>
<httpModules>
<add name="UrlRemapper" type="UrlRemapper" />
</httpModules>
</system.web>
第三步:将映射关系存放在XML文件中
<?xml version="1.0" encoding="utf-8" ?>
<urlMappings>
<add url="~/HomeSource.aspx" mappedUrl="~/HomeTo.aspx"/>
<!--<add url="~/HomeSource.aspx" mappedUrl="~/HomeTo.aspx"/>-->
</urlMappings>