Asp.net URL重写(URLRewriter)

可以使用 ISAPI 筛选器在 IIS Web 服务器级别实现 URL 重写,也可以使用 HTTP 模块或 HTTP 处理程序在 ASP.NET 级别实现 URL 重写。
在dotnet中如果实现URLRewriter只需做如下几步:

第一步:添加dll引用 URLRewriter.dll

第二步:在web.config文件中进行配置


先加入一个section节

<configuration>
    .......
  
<configSections>
    
<section name="RewriterConfig" type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter"/>
  
</configSections>

然后加入一个模块httpMoudles,

为 URL 重写引擎指定配置信息


<system.web>
。。。。。
<httpModules>
      
<add type="URLRewriter.ModuleRewriter, URLRewriter" name="ModuleRewriter"/>
    
</httpModules>

注意节的位置 
<system.web><configSections>两个节是平级的

再加入规则
<RewriterConfig>
      
<Rules>
        
<!-- Rules for Blog Content Displayer -->
        
<RewriterRule>
          
<LookFor>/ctrl/(.*).ashx</LookFor>
          
<SendTo>/ControlContainer.aspx?control=/ctrl/$1.ascx</SendTo>
        
</RewriterRule>
        
<RewriterRule>
          
<LookFor>ctrl/(.*).ashx</LookFor>
          
<SendTo>/ControlContainer.aspx?control=ctrl/$1.ascx</SendTo>
        
</RewriterRule>
      
</Rules>
    
</RewriterConfig>

这个节与<system.web>平级
注意sendto节中的路径这块设置不好,会报404错误的!
这里的意思是凡是从路径http://.../ctrl/111.ashx来的请求都由/ControlContainer.aspx?control=/ctrl/111.ascx来处理


除了指定使用 HTTP 模块还是 HTTP 处理程序执行重写外,Web.config 文件还包含重写规则:重写规则由两个字符串组成:要在被请求的 URL 中查找的模式;要替换此模式的字符串(如果找到)。在 Web.config 文件中,此信息是使用以下语法表达的:

<RewriterConfig>
<Rules>
<RewriterRule>
<LookFor>要查找的模式</LookFor>
<SendTo>要用来替换模式的字符串</SendTo>
</RewriterRule>
<RewriterRule>
<LookFor>要查找的模式</LookFor>
<SendTo>要用来替换模式的字符串</SendTo>
</RewriterRule>
...
</Rules>
</RewriterConfig>

每个重写规则均由 <RewriterRule> 元素表达。要搜索的模式由 <LookFor> 元素指定,而要替换所找到的模式的字符串将在 <SentTo> 元素中输入。这些重写规则将从头到尾进行计算。如果发现与某个规则匹配,URL 将被重写,并且对重写规则的搜索将会终止。

在 <LookFor> 元素中指定模式时,请注意,要使用正则表达式来执行匹配和字符串替换。(稍后,我们将介绍一个真实的示例,说明如何使用正则表达式来搜索模式。)由于模式是正则表达式,应确保转义正则表达式中的任何保留字符。(一些正则表达式保留字符包括:.、?、^、$ 及其他。可以通过在前面加反斜杠(如 \.)对这些字符进行转义,以匹配文字句点。)



原文地址:https://www.cnblogs.com/goody9807/p/952375.html