URL重定向(用数据库存取配置)
基本的URL重定向实现:
http://www.cnblogs.com/aqiang/archive/2008/02/27/1083710.html
http://www.cnblogs.com/sunfny/archive/2011/2/21.html
在官网:http://www.urlrewriting.net/ 上下载的DLL是利用web.config配置实现的,现在要改变存取方式,需要对源码重新整理一次
用这种方式实现的重定向,可以更加方便管理,而且对于自定义后缀名(如把.html改成.xyz)这种需求,直接输入配置即可,不需要配置其它东西(如IIS)
1、获取URLRewriter的DLL。创建HttpModule类,实现IHttpModule接口,在Init函数中为HttpApplication对象的AuthorizeRequest添加委托事件,在事件中读取数据库配置,最终通过HttpContext对象的RewritePath方法实现重定向。
/// 实现IHttpModule的抽象类
/// </summary>
public abstract class BaseModuleRewriter : IHttpModule
{
public virtual void Init(HttpApplication app)
{
//当安全模块已验证用户授权时发生
app.AuthorizeRequest += new EventHandler(this.BaseModuleRewriter_AuthorizeRequest);
}
public virtual void Dispose() { }
protected virtual void BaseModuleRewriter_AuthorizeRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
Rewrite(app.Request.Url.AbsoluteUri, app);
}
/// <summary>
/// 地址重写抽象函数
/// </summary>
/// <param name="requestedPath"></param>
/// <param name="app"></param>
protected abstract void Rewrite(string requestedPath, HttpApplication app);
}
{
/// <summary>
/// 地址重写函数
/// </summary>
/// <param name="requestedPath"></param>
/// <param name="app"></param>
protected override void Rewrite(string requestedPath, System.Web.HttpApplication app)
{
//开始跟踪日志
app.Context.Trace.Write("ModuleRewriter", "Entering ModuleRewriter");
//获取规则集合
Hashtable hash = RewriterConfig.GetHash();
foreach (DictionaryEntry de in hash)
{
string u_Url = @"^" + de.Key.ToString() + "$";
Regex re = new Regex(u_Url, RegexOptions.IgnoreCase);
if (re.IsMatch(requestedPath))
{
string sendToUrl = RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(requestedPath, de.Value.ToString()));
app.Context.Trace.Write("ModuleRewriter", "Rewriting URL to " + sendToUrl);
RewriterUtils.RewriteUrl(app.Context, sendToUrl);
break;
}
}
//结束跟踪日志
app.Context.Trace.Write("ModuleRewriter", "Exiting ModuleRewriter");
}
}
{
/// <summary>
/// 从数据库中读取配置
/// </summary>
/// <returns></returns>
public static Hashtable GetHash()
{
Hashtable hash = new Hashtable();
//正式上线后需要启用cache减少IO操作
//string key = "Rewriter_GetHash";
//object o = System.Web.HttpRuntime.Cache[key];
//if (o == null)
//{
// HttpContext.Current.Trace.Warn("o is null");
try
{
string connStr = System.Configuration.ConfigurationManager.AppSettings["Rewriter_Conn"];
string table = System.Configuration.ConfigurationManager.AppSettings["Rewriter_Table"];
string fromCol = System.Configuration.ConfigurationManager.AppSettings["Rewriter_FromCol"];
string toCol = System.Configuration.ConfigurationManager.AppSettings["Rewriter_ToCol"];
string sql = "select " + fromCol + "," + toCol + " from " + table;
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader Reader = cmd.ExecuteReader();
while (Reader.Read())
{
hash.Add(Reader[fromCol].ToString(), Reader[toCol].ToString());
}
Reader.Close();
conn.Close();
//System.Web.HttpRuntime.Cache.Insert(key, hash, null, DateTime.Now.AddHours(12), TimeSpan.Zero);
}
catch (Exception exp) { HttpContext.Current.Trace.Warn(exp.Message); }
//}
//else
//{
// HttpContext.Current.Trace.Warn("o was cached");
// hash = (Hashtable)o;
//}
return hash;
}
}
{
internal static void RewriteUrl(HttpContext context, string sendToUrl)
{
string x, y;
RewriteUrl(context, sendToUrl, out x, out y);
}
internal static void RewriteUrl(HttpContext context, string sendToUrl, out string sendToUrlLessQString, out string filePath)
{
//为转向地址加上原请求参数
if (context.Request.QueryString.Count > 0)
{
if (sendToUrl.IndexOf('?') != -1) sendToUrl += "&" + context.Request.QueryString.ToString();
else sendToUrl += "?" + context.Request.QueryString.ToString();
}
string queryString = String.Empty;
sendToUrlLessQString = sendToUrl;
if (sendToUrl.IndexOf('?') > 0)
{
sendToUrlLessQString = sendToUrl.Substring(0, sendToUrl.IndexOf('?'));
queryString = sendToUrl.Substring(sendToUrl.IndexOf('?') + 1);
}
filePath = string.Empty;
filePath = context.Server.MapPath(sendToUrlLessQString);
//地址重写
context.RewritePath(sendToUrlLessQString, String.Empty, queryString);
}
internal static string ResolveUrl(string appPath, string url)
{
if (url.Length == 0 || url[0] != '~') return url;
else
{
if (url.Length == 1) return appPath;
if (url[1] == '/' || url[1] == '\\')
{
if (appPath.Length > 1) return appPath + "/" + url.Substring(2);
else return "/" + url.Substring(2);
}
else
{
if (appPath.Length > 1) return appPath + "/" + url.Substring(1);
else return appPath + url.Substring(1);
}
}
}
}
2、将数据库的信息配置到web.config中,用最原始的DB操作去完成读取
<add key="Rewriter_Conn" value="server=xxx;database=xxx;uid=xxx;pwd=xxx"/>
<!-- 存放配置的表名-->
<add key="Rewriter_Table" value="TableName"/>
<!-- 存放正则表达式的列名-->
<add key="Rewriter_FromCol" value="FromCol"/>
<!-- 存放匹配成功后跳转地址的列名-->
<add key="Rewriter_ToCol" value="ToCol"/>
3、WEB项目添加DLL引用,web.config的httpModules节点添加:
<!-- type:最终实现IHttpModule的类,生成的DLL文件名,name:自定义模块名-->
<add type="URLRewriter.ModuleRewriter, URLRewriter" name="ModuleRewriter" />
4、在数据库中添加配置信息,如:
FromCol:http://(.*/?)/help_(\d+).html 对应跳转 ToCol:/Info/Arcticle.aspx?id=$2