using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;
/// <summary>
/// URL重写Module
/// </summary>
public class UrlRewriteModule : IHttpModule
{
#region IHttpModule Members
public virtual void Init(HttpApplication context)
{
context.BeginRequest += ApplicationBeginRequest;
}
public virtual void Dispose()
{
}
#endregion
public bool IsExcludedPath(string relUrl)
{
string fileExt = Path.GetExtension(relUrl);
if (!string.IsNullOrEmpty(fileExt)
&& (fileExt.ToLower() == ".axd" ||
fileExt.ToLower() == ".jpg" ||
fileExt.ToLower() == ".png" ||
fileExt.ToLower() == ".gif" ||
fileExt.ToLower() == ".swf" ||
fileExt.ToLower() == ".bmp"
))
{
return true;
}
return false;
}
/// <summary>
///
/// </summary>
/// <param name="source"></param>
/// <param name="e"></param>
public void ApplicationBeginRequest(object source, EventArgs e)
{
var application = (HttpApplication)source;
HttpContext context = application.Context;
try
{
string path = context.Request.Path;
string file = Path.GetFileName(path);
if (IsExcludedPath(path))
{
return;
}
if (file != null && HttpContext.Current != null)
{
string rewriteConfig = HttpContext.Current.Server.MapPath("~/Config/RewriterConfig.config");
if (File.Exists(rewriteConfig))
{
var xml = new XmlDocument();
xml.Load(rewriteConfig);
XmlNodeList rules = xml.SelectNodes("RewriterConfig/Rules/RewriterRule");
if (rules != null)
{
foreach (XmlNode rule in rules)
{
string lookFor = "";
string sendTo = "";
XmlNode lookForNode = rule.SelectSingleNode("LookFor");
if (lookForNode != null)
{
lookFor = lookForNode.InnerText;
}
XmlNode sendToNode = rule.SelectSingleNode("SendTo");
if (sendToNode != null)
{
sendTo = sendToNode.InnerText;
}
if (!string.IsNullOrEmpty(lookFor) && !string.IsNullOrEmpty(sendTo))
{
string regeRule = Regex.Escape(lookFor);
var regex = new Regex("^(?i)" + regeRule + "$", RegexOptions.Compiled);
//匹配无后缀时路径
if (string.IsNullOrEmpty(file))
{
if (context.Request.ApplicationPath != null)
{
var subPath = path.Substring(context.Request.ApplicationPath.Length).TrimStart('/').TrimEnd('/');
if (regex.Match(subPath).Success)
{
context.RewritePath(Path.Combine(context.Request.ApplicationPath, sendTo));
break;
}
}
}
else
{
if (regex.Match(file).Success)
{
context.RewritePath(sendTo);
break;
}
}
}
}
}
}
}
}
catch (Exception ex)
{
context.Response.Clear();
context.Response.Write(ex.Message);
context.Response.End();
}
}
}
<?xml version="1.0"?>
<RewriterConfig>
<Rules>
<RewriterRule>
<LookFor>floor</LookFor>
<SendTo>index_floor.html</SendTo>
</RewriterRule>
<RewriterRule>
<LookFor>door</LookFor>
<SendTo>about/index_292.html</SendTo>
</RewriterRule>
<RewriterRule>
<LookFor>kolani</LookFor>
<SendTo>index_kolani.html</SendTo>
</RewriterRule>
<RewriterRule>
<LookFor>nature</LookFor>
<SendTo>index_nature.html</SendTo>
</RewriterRule>
<RewriterRule>
<LookFor>mobile</LookFor>
<SendTo>index_mobile.html</SendTo>
</RewriterRule>
</Rules>
</RewriterConfig>