日期:2010-09-24 浏览次数:20591 次
以前用url重写时是用的ms urlrewriter,用了以后发现了很多不足,自定义功能太弱,而且随着重写规则的增加,web.config可能会越来越大,实际上,url重写就是实现IHttpHandler接口.
整个流程分二步走:
1、用一个xml文件来存储重写规则,其中这些规则是一些简单的正则表达式
2、实现IHttpHandler接口
首先看一下xml文件的格式:
<?xml version="1.0" encoding="utf-8" ?>
<root>
<regex>
<!--重写以后的虚拟地址-->
<b><![CDATA[xxx,(?<id>[0-9]+).html$]]></b>
<!--实际地址-->
<a><![CDATA[xxx.aspx?id=${id}]]></a>
</regex>
</root>
相信上面的xml大家都能看懂.
using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.VisualBasic;
//RegexInfo结构,用来存储从xml文件中读取到的数据
public struct RegexInfo
{
public string _before;
public string _after;
public RegexInfo(string before, string after)
{
_before = before.ToLower();
_after = after.ToLower();
}
}
//ipFilter结构,用来存储被封的IP
public struct ipFilter
{
public string _ip;
public ipFilter(string ip)
{
_ip = ip;
}
}
public class HtmlHttpHandler : IHttpHandler //实现IHttpHandler接口
{
private List<RegexInfo> _regex_list = new List<RegexInfo>();
private List<ipFilter> _ip_filter = new List<ipFilter>();
public HtmlHttpHandler()
{
DataSet ds = new DataSet();
//读取url重写规则文件,并写入RegexInfo结构的实例中
ds.ReadXml(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Regexs.xml"));
foreach (DataRow r in ds.Tables["regex"].Rows)
_regex_list.Add(new RegexInfo(((string)r["b"]).Trim(), ((string)r["a"]).Trim()));
ds.Reset();
//读取被封的IP列表
ds.ReadXml(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/ipFilter.xml"));
foreach(DataRow r in ds.Tables["IpFilters"].Rows)
_ip_filter.Add(new ipFilter((string)r["ip"]));
}
public void ProcessRequest(HttpContext context)
{
string _ip = context.Request.UserHostAddress; &nb