如何处理web.config重写规则中的特殊字符?

时间:2017-09-07 18:55:37

标签: asp.net url-rewriting web-config special-characters

当URL包含特殊字符时,我的重写规则出错:

此网址http://www.example.com/bungalow/rent/state/texas/street/exloër/exloër 使用此重写规则:

    <rule name="rentals by proptype+state+city+street">
      <match url="^([a-zA-Z0-9-+]+)/rent/state/([a-zA-Z-+]+)/street/([a-zA-Zë-+]+)/([0-9a-zA-Zë-+']+)$" />
      <action type="Rewrite" url="search_new.aspx?proptype={R:1}&amp;state={R:2}&amp;city={R:3}&amp;street={R:4}" />
    </rule>

导致500错误

此网址http://www.example.com/bungalow/rent/state/texas/street/exloër/exloër 使用此重写规则:

    <rule name="rentals by proptype+state+city+street">
      <match url="^([a-zA-Z0-9-+]+)/rent/state/([a-zA-Z-+]+)/street/([a-zA-Z-+]+)/([0-9a-zA-Z-+']+)$" />
      <action type="Rewrite" url="search_new.aspx?proptype={R:1}&amp;state={R:2}&amp;city={R:3}&amp;street={R:4}" />
    </rule>

导致404错误

如何处理重写规则中的特殊字符?

更新1

相关网址带有ë字符,但是当我复制地址时,它会转义为%c3%abr 根据此规则,我仍然会收到404错误:

    <rule name="rentals by proptype+state+city+street">
      <match url="^([a-zA-Z0-9-+]+)/rent/state/([a-zA-Z-+]+)/street/([a-zA-Z%-+]+)/([0-9a-zA-Z%-+']+)$" />
      <action type="Rewrite" url="search_new.aspx?proptype={R:1}&amp;state={R:2}&amp;city={R:3}&amp;street={R:4}" />
    </rule>

所以我想真正的问题是,如何在重写规则中处理%个字符?

1 个答案:

答案 0 :(得分:2)

你的最后一次尝试几乎是正确的正则表达式,你只有一个小错误(忘了添加0-9到第三个块)。正确的正则表达式是:

^([a-zA-Z0-9-+]+)/rent/state/([a-zA-Z-+]+)/street/([a-zA-Z0-9%-+]+)/([0-9a-zA-Z%-+']+)$

但在重写规则中,您需要使用变量{UNENCODED_URL}

工作示例是:

<rule name="rentals by proptype+state+city+street" stopProcessing="true">
    <match url=".*" />
    <conditions>
        <add input="{UNENCODED_URL}" pattern="^/([a-zA-Z0-9-+]+)/rent/state/([a-zA-Z-+]+)/street/([a-zA-Z0-9%-+]+)/([0-9a-zA-Z%-+']+)$" />
    </conditions>
    <action type="Rewrite" url="search_new.aspx?proptype={C:1}&amp;state={C:2}&amp;city={C:3}&amp;street={C:4}" />
</rule>

<强> UPD

来自评论的例子:

您的网址:http://www.example.com/bungalow/rent/state/north-dakota/stre et / savanah /%27s-gr acland有一些隐藏的特殊字符(即使SO无法正确解析它)。您可以在此处查看其编码方式:https://www.urlencoder.org/

因此我更改了规则中的正则表达式,如下所示:

<rule name="rentals by proptype+state+city+street" stopProcessing="true">
    <match url=".*" />
    <conditions>
        <add input="{UNENCODED_URL}" pattern="^/([a-zA-Z0-9\-+]+)/rent/state/([a-zA-Z\-+]+)/([a-zA-Z0-9%\-+]+)/([a-zA-Z0-9%\-+]+)/([0-9a-zA-Z%\-+']+)$" />
    </conditions>
    <action type="Rewrite" url="search_new.aspx?proptype={C:1}&amp;state={C:2}&amp;city={C:4}&amp;street={C:5}" />
</rule>