首页 > 解决方案 > IIS web.config重写规则条件输入内两个捕获组的比较

问题描述

我正在尝试比较 IIS web.config 中重写 url 的条件输入中的两个捕获组。

我需要这样做,因为如果他们的语言代码 cookie 与 URL 中的语言不匹配,我不希望用户访问特定于语言的 URL(例如 /en/path)。

我试图在我的 webconfig 中使用此规则来实现,但似乎无法这样做,因为服务器以 500.52 错误回答:

The expression "^((?!{C:2}).)*$" contains a repeat expression (one of '*', '?', '+', '{' in most contexts) that is not preceded by an expression.

它将我的 {C:2} 作为正则表达式本身的一部分,而不是原始字符串。

这是完整的规则:

<rule name="redirect-with-lang" stopProcessing="true">
      <match url="en\/|es\/|mx\/" ignoreCase="true"/>
      <conditions logicalGrouping="MatchAll" trackAllCaptures="true">
        <add input="{HTTP_COOKIE}" pattern="langpref=\w{2}\/(\w{2});" />
        <add input="{REQUEST_URI}" pattern="^(\/es\/|\/en\/|\/mx\/).+$" />
        <add input="{C:1}" pattern="^((?!{C:2}).)*$"/>
      </conditions>
      <action type="Redirect" url="/{C:1}/{C:3}" />
    </rule>

我想知道是否可以在不借助 javascript 或 Global.asax 上的某些服务器代码的情况下以另一种方式实现这一目标。

谢谢

标签: c#regexasp.net-mvciisweb-config

解决方案


您可以使用此 <add input="{C:1}" pattern="^((?!\{C:2\}).)*$"/>条件而不是<add input="{C:1}" pattern="^((?!{C:2}).)*$"/>

由于大括号 - { } 在条件中,您会收到此错误。


推荐阅读