使用IHttpHandler进行重定向过程中遇到的困惑

  在上文在Asp.Net里使用自定义映射进行重定向 中,如果在配置节里没有找到匹配的重定向地址时,应该怎么执行当前的地址呢。

  比如在web.config里定义如下
  <URLRewriterConfig>
    
<Rules>
       
<URLRewriterRule>
         
<MatchUrl>show_([\d]+)\.aspx</MatchUrl>
         
<RedirectUrl><![CDATA[target.aspx?to=$1]]></RedirectUrl>
       
</URLRewriterRule>
     
</Rules>
  
</URLRewriterConfig>
 <httpHandlers>
   
<add verb="POST,GET" path="show_*.aspx" type="FaibClass.Common.Web.URLRewriterHandler, FaibClass.Common" />
  
</httpHandlers>

  这样,只要符合show_*.aspx的页面都会使用URLRewriterHandler,但如果是站内存在这样的文件 show_article.aspx ,那也将会被重定向到target.aspx执行。但是,该url并不会在URLRewriterConfig里找到匹配的项,因此,页面就无任何输出。

  试着这样修改ProcessRequest过程:
 1        public void ProcessRequest(HttpContext context)
 2        {
 3            URLRewriterRuleCollection rules = URLRewriterConfiguration.GetConfig().Rules;
 4            string requestedPath = context.Request.FilePath;
 5            for(int i = 0; i < rules.Count; i++)
 6            {
 7                Regex reg = new Regex(rules[i].MatchUrl, RegexOptions.IgnoreCase);
 8                bool isMatch = reg.IsMatch(requestedPath);
 9                if(isMatch)
10                {
11                    context.Server.Execute(reg.Replace(requestedPath, rules[i].RedirectUrl));
12                    return;
13                }

14            }

15            context.Server.Execute(requestedPath); // 这里发生错误:子请求无效
16        }

17
  这样做并没有得到预期的效果,反而发生了一个错误:子请求无效。试着使用context.Current.Response.Redirect更是使页面在这期间重复来回。

  所以,使用IHttpHandler实现重定向是不是真的不太理想呢,急希望各位高手指点指点。
原文地址:https://www.cnblogs.com/faib/p/719892.html