一个URL重写的例子

打开 Global.asax.cs 在最上面添加一行 using System.Text.RegularExpressions;

然后在 Application_BeginRequest 事件中写入

string strRawUrl = HttpContext.Current.Request.RawUrl;
string strNewUrl;

if (Regex.IsMatch(strRawUrl, @"default.aspx", RegexOptions.IgnoreCase))
{
strNewUrl 
= Regex.Replace(strRawUrl, @"default.aspx"@"showforum.aspx\?fld=1");

HttpContext.Current.RewritePath( strNewUrl );
}

else if (Regex.IsMatch(strRawUrl, @"(\d+)0(\d+)0(\d+)0(\d+).html", RegexOptions.IgnoreCase))
{
strNewUrl 
= Regex.Replace(strRawUrl, @"(\d+)0(\d+)0(\d+)0(\d+).html"@"showtopic.aspx\?tid=$1&tpg=$2&bpg=$3&fld=$4");

HttpContext.Current.RewritePath( strNewUrl );
}

else if (Regex.IsMatch(strRawUrl, @"showtopic.aspx\?tid=(\d+)&tpg=(\d+)&bpg=(\d+)&fld=(\d+)", RegexOptions.IgnoreCase))
{
strNewUrl 
= Regex.Replace(strRawUrl, @"showtopic.aspx\?tid=(\d+)&tpg=(\d+)&bpg=(\d+)&fld=(\d+)"@"$10$20$30$4.html");

HttpContext.Current.Response.Redirect( strNewUrl );
}


第一个IF是最最简单的

第二个IF是当IIS把HTML交给ASP.NET时使用的,嘿嘿

第三个IF是为了解决表单提交时IE的地址栏出现真实的URL地址,是第二个IF的逆操作

其中正则表达式里的0是分隔符,因为页数、ID的最小址都不可能是0
用户IE的地址栏中显示的是http://localhost/AdNT/4561230100101.html
但实际上是http://localhost/AdNT/showtopic.aspx?tid=456123&tpg=10&bpg=1&fld=1

posted @ 2005-09-04 13:47  冰戈  阅读(1303)  评论(1编辑  收藏  举报