C# URL 重写与反重写
在URL重写中,最重要的莫过于IHttpModule接口了,先看下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace YouXi.Components
{
public class HttpModule : IHttpModule
{
#region IHttpModule 成员
void IHttpModule.Dispose()
{
}
void IHttpModule.Init(HttpApplication context)
{
//在页面读取开始时,这里每个页面都会先运行
context.BeginRequest += new EventHandler(context_BeginRequest);
}
void context_BeginRequest(object sender, EventArgs e)
{
//这儿处理url重写
UrlRewriter.Rewriter();
}
#endregion
}
}
UrlRewriter类,重写URL,并设置重写路径,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace YouXi.Components
{
public class UrlRewriter
{
/// <summary>
/// url路径重写
/// </summary>
/// <param name="rawUrl"></param>
public static void Rewriter()
{
//这儿处理url重写
//string s_NewUrl = null;
//bool IsMatch = false;
HttpRequest req = HttpContext.Current.Request;
string rawUrl = req.Url.ToString();//.Remove(0, 7).ToLower();
if (!rawUrl.EndsWith(".shtm"))
return;
if(CommonHelper.UrlReWriterHelper.Rewrite(ref rawUrl))
HttpContext.Current.RewritePath(rawUrl);
}
}
}
重写初始化类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Xml;
using System.Text.RegularExpressions;
namespace CommonHelper
{
public class UrlReWriterHelper
{
private static string configFile = "/Configs/UrlReWriter.Config";
public List<UrlReWriterRule> Rules;
private static UrlReWriterHelper Instance { get; set; }
private bool _Enabled;
private bool _Reverse;
/// <summary>
/// 反向匹配
/// </summary>
public bool Reverse
{
get { return _Reverse; }
}
/// <summary>
/// 正向匹配
/// </summary>
public bool Enabled
{
get { return _Enabled; }
}
/// <summary>
/// 初始化重写规则
/// </summary>
static UrlReWriterHelper()
{
Instance = new UrlReWriterHelper();
Instance.Rules = new List<UrlReWriterRule>();
string file = HttpContext.Current.Server.MapPath(configFile);
XmlDocument xd = new XmlDocument();
xd.Load(file);
XmlElement xe = xd.DocumentElement;
bool enabled = true;
if (xe.Attributes["enabled"] != null)
{
enabled = Boolean.TryParse(xe.Attributes["enabled"].Value, out enabled);
}
Instance._Enabled = enabled;
bool reverse = true;
if (xe.Attributes["reverse"] != null)
{
reverse = Boolean.TryParse(xe.Attributes["reverse"].Value, out reverse);
}
Instance._Reverse = reverse;
foreach (XmlNode xn in xe.ChildNodes)
{
if (xn.NodeType == XmlNodeType.Element)
{
UrlReWriterRule re = new UrlReWriterRule(xn);
Instance.Rules.Add(re);
}
}
}
/// <summary>
/// 按配置的规则进行路径重写并将最后值改写给参数,返回值表示是否进行重写
/// </summary>
/// <param name="rawUrl">可以根据此值进行重写操作</param>
/// <returns></returns>
public static bool Rewrite(ref string rawUrl)
{
if (string.IsNullOrEmpty(rawUrl.Trim()))
return false;
UrlReWriterHelper config = UrlReWriterHelper.Instance;
if (!config.Enabled)
return false;
List<UrlReWriterRule> Rules = config.Rules;
if (Rules == null || Rules.Count == 0)
return false;
foreach (UrlReWriterRule rule in Rules)
{
Regex r = new Regex(rule.Pattern, RegexOptions.IgnoreCase);
if (r.IsMatch(rawUrl))
{
string s_url = r.Replace(rawUrl, rule.Url);
rawUrl = s_url.Replace("/","/");
int start = rawUrl.IndexOf("/", 7);
if (start == 0)
return true;
rawUrl = rawUrl.Substring(start);
return true;
}
}
return false;
}
}
}
UrlReWriterRule规则类,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace CommonHelper
{
/// <summary>
/// URL重写配置项
/// </summary>
public class UrlReWriterRule
{
#region
private string _Pattern;
private string _Url;
private string _RePattern;
private string _ReUrl;
#endregion
#region
/// <summary>
/// 反向重写后的路径
/// </summary>
public string ReUrl
{
get { return _ReUrl; }
}
/// <summary>
/// 反向原始路径
/// </summary>
public string Repattern
{
get { return _RePattern; }
}
/// <summary>
/// 正向重写后的路径
/// </summary>
public string Url
{
get { return _Url; }
}
/// <summary>
/// 正向原始路径
/// </summary>
public string Pattern
{
get { return _Pattern; }
}
#endregion
public UrlReWriterRule()
{
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="xn">XML节点</param>
public UrlReWriterRule(XmlNode xn)
{
try
{
if (xn.SelectSingleNode("pattern") != null)
_Pattern = xn.SelectSingleNode("pattern").InnerText;
else if(xn.Attributes["pattern"]!=null)
_Pattern = xn.Attributes["pattern"].Value;
if (xn.SelectSingleNode("url") != null)
_Url = xn.SelectSingleNode("url").InnerText;
else if (xn.Attributes["url"] != null)
_Url = xn.Attributes["url"].Value;
if (xn.SelectSingleNode("repattern") != null)
_RePattern = xn.SelectSingleNode("repattern").InnerText;
else if (xn.Attributes["repattern"] != null)
_RePattern = xn.Attributes["repattern"].Value;
if (xn.SelectSingleNode("reurl") != null)
_ReUrl = xn.SelectSingleNode("reurl").InnerText;
else if (xn.Attributes["reurl"] != null)
_ReUrl = xn.Attributes["reurl"].Value;
}
catch (Exception e)
{
throw (e);
}
}
}
}
UrlReWriter.Config 重写规则config文件
<?xml version="1.0" encoding="utf-8" ?>
<UrlReWriter enabled="true" reverse="false">
<!--链接到其他刚站的URL中转-->
<url pattern="/go/(d+).shtm" url="/go/reurl.ashx?urlid=$1"
repattern="^/games/reurl.ashx?urlid=(d+)$" reurl="/games/$1.shtm"></url>
<!--Tags页面-->
<url pattern="/tags/([^/.]+).shtm" url="/go/TagGameList.aspx?tagName=$1"
repattern="^/go/TagGameList.aspx?tagName=([wW+]+)$" reurl="/tags/$1.shtm"></url>
<!--Tags页面-->
<url pattern="/tags/([^/]+)/(d+).shtm" reurl="/tags/$1/$2.shtm">
<url>
<![CDATA[/go/TagGameList.aspx?tagName=$1&pageIndex=$2]]></url>
<repattern><![CDATA[^/go/TagGameList.aspx?tagName=([^&]+)&(d+)$]]></repattern>
</url>
</UrlReWriter>