【问题标题】:Accessing MatchedParameters from an if statement in set-body从 set-body 中的 if 语句访问 MatchedParameters
【发布时间】:2021-01-06 06:59:25
【问题描述】:

在 REST API 的 APIM 策略中,我尝试为后端服务创建 SOAP 请求。 REST 请求的 URI 是 /GetCustomer/{accountNumber}。 在下面的 Liquid if 语句中,我试图检查 MatchedParameters 集合是否包含帐号。这不起作用,我从 else 分支获取值。 我尝试了几种变体:

  1. {% if {{context.Request.MatchedParameters.ContainsKey("accountNumber")}} %}
  2. {% if @(context.Request.MatchedParameters.ContainsKey("accountNumber")) %}
  3. {% if context.Request.MatchedParameters.ContainsKey("accountNumber") %}
<set-body template="liquid">
            <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns="http://my-services.com/CustomerService/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                <soap:Body>
                    <GetCustomer>
                        <request>
                            {% if {{context.Request.MatchedParameters.ContainsKey("accountNumber")}} %}
                            <AccountNumber>{{context.Request.MatchedParameters["accountNumber"]}}</AccountNumber>
                            {% else %}
                            <AccountNumber xsi:nil="true" />
                            {% endif %}
                        </request>
                    </GetCustomer>
                </soap:Body>
            </soap:Envelope>
        </set-body>

离开 if 语句可以正常工作,然后按我的预期构造请求:

<set-body template="liquid">
            <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns="http://my-services.com/CustomerService/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                <soap:Body>
                    <GetCustomer>
                        <request>                           
                            <AccountNumber>{{context.Request.MatchedParameters["accountNumber"]}}</AccountNumber>
                        </request>
                    </GetCustomer>
                </soap:Body>
            </soap:Envelope>
        </set-body>

所以问题是:是否可以从 Liquid if 语句中访问上下文?如果是这样,正确的语法是什么?

【问题讨论】:

    标签: azure-api-management


    【解决方案1】:

    我在我这边测试一下,你只需要把液体写成这样:

    {% if context.Request.MatchedParameters["accountNumber"] != null %}
        
    {% else %}
        
    {% endif %}
    

    顺便说一句:根据我的测试,如果你在APIM的请求url中指定了一个{accountNumber}。我们必须用...../GetCustomer/{accountNumber} 请求它,如果我们用...../GetCustomer 请求它,它将显示404 错误。所以你不必担心“如果 context.Request.MatchedParameters["accountNumber"] 存在

    【讨论】:

    • 在这种情况下你是对的,accountNumber 是必需的。在其他情况下,我必须检查作为查询字符串传递的可选值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多