Url重写小例

1.IHttpModule接口实现:

namespace AspNetUnleashed
{
public class UrlRemapper : IHttpModule
{
public void Init(HttpApplication app)
{
app.BeginRequest
+= new EventHandler(app_BeginRequest);
}

public void app_BeginRequest(Object s, EventArgs e)
{
// Get HTTP Context
HttpApplication app = (HttpApplication)s;
HttpContext context
= app.Context;

// Get current URL
string currentUrl = context.Request.AppRelativeCurrentExecutionFilePath;

// Get URL Mappings
XmlDocument urlMappings = GetUrlMappings(context);

// Compare current URL against each URL from mappings file
XmlNodeList nodes = urlMappings.SelectNodes("//add");
foreach (XmlNode node in nodes)
{
string url = node.Attributes["url"].Value;
string mappedUrl = node.Attributes["mappedUrl"].Value;
if (Regex.Match(currentUrl, url, RegexOptions.IgnoreCase).Success)
context.RewritePath(mappedUrl);
}
}

private XmlDocument GetUrlMappings(HttpContext context)
{
XmlDocument urlMappings
= (XmlDocument)context.Cache["UrlMappings"];
if (urlMappings == null)
{
urlMappings
= new XmlDocument();
string path = context.Server.MapPath("~/UrlMappings.config");
urlMappings.Load(path);
CacheDependency fileDepend
= new CacheDependency(path);
context.Cache.Insert(
"UrlMappings", urlMappings, fileDepend);

}
return urlMappings;
}

public void Dispose() { }

}
}

BeginRequest 事件处理程序从名为UrlMappings.config的XML配置文件中得到一个Url重映射列表。XML配置文件 
UrlMappings.config中的内容缓存在服务器端内存中,知道硬盘上的
UrlMappings.config被修改之后再次载入。
接下来,该模块使用从XML配置文件中获得的重映射条目,并使用正则进行匹配,如果成功,使用 context.RewritePath方法
把当前路径映射为重映射路径。

2.
UrlMappings.config配置文件:
<?xml version="1.0"?>
<urlMappings>
<add
url="~/Home.aspx"
mappedUrl
="~/Default.aspx" />
<add
url="/Products/.*"
mappedUrl
="~/Products/Default.aspx" />
</urlMappings>

3.Web.config:
<system.web>
<httpModules>
<add name="UrlRemapper" type="AspNetUnleashed.UrlRemapper"/>
</httpModules>
</system.web>


posted on 2011-05-13 01:16  Scarface  阅读(323)  评论(0编辑  收藏  举报

导航