使用Url Rewrite 如果原始Url就带QueryString时候的一个问题

我重写了我的站点程序,在使用msdn内
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspp/html/urlrewriting.asp
关于Url Rewrite的方法

今天发现发现搜索引擎内对于原访问地址的记录还都在,而且有很多朋友通过这些地址访问
我当然不愿意然这些连接全部导向出错页面了,就想在Url Rewirte 内加个规则
<LookFor>为~/ShowArticle.Aspx\?ID=(\d+)
<SendTo>为~/Show.Aspx\?ID=(\d+)
当我这么加了后,访问该页面发现报错误404
仔细看Url Write的代码
最后发现


protected virtual void RewriterModule_AuthorizeRequest(object sender, EventArgs e)
{
 HttpApplication app = (HttpApplication)sender;
 Rewrite(app.Request.Path, app);//看这里,采用的是Request.Path 
}

经过我测试
对一个地址http://localhost/test/requestpath.aspx/sss.aspx?id=2222访问
得到的结果是

request.path:       /test/requestpath.aspx/sss.aspx
Request.Url.ToString():     http://localhost/test/requestpath.aspx/sss.aspx?id=2222
Request.PathInfo:    /sss.aspx
Request.RawUrl:     /test/requestpath.aspx/sss.aspx?id=2222

我将上面的代码改成

protected virtual void RewriterModule_AuthorizeRequest(object sender, EventArgs e)
{
 HttpApplication app = (HttpApplication)sender;
 Rewrite(app.Request.RawUrl, app); 
}

执行我的程序,发现我的程序报错,提示的是我的参数不正确,
跟踪了一下发现QueryString传递了两个ID参数
经过跟踪代码,发现 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();
 }
}
这里将context.Request.QueryString又给sendToUrl加了一边
如果去掉这部分那么虚拟的没有QueryString参数的页面将全部无法传递正确
最后只有在些Rewrite.config的时候

<!--
 如果LookFor内包含QueryString那么在SendTo内就不必写QueryString,
 因为上下文的content的context.Request.QueryString已经传递过去了
-->
<RewriterRule>
 <LookFor>~/ShowArticle.Aspx\?ID=(\d+)</LookFor>
 <SendTo><![CDATA[~/Show.aspx]]></SendTo><!--这里-->
</RewriterRule>

 一切ok了,这样的地址都能访问了
http://www.aspxboy.com/ShowArticle.Aspx?ID=214
 :-)
 

posted on 2005-09-24 19:14  活靶子.Net  阅读(2026)  评论(0编辑  收藏  举报

导航