【问题标题】:Validate request parameters in Azure APIM在 Azure APIM 中验证请求参数
【发布时间】:2024-05-01 13:45:02
【问题描述】:

我定义了一个full-name API,它接受名字和姓氏并将它们组合起来以返回全名:

https://my-org.azure-api.net/my-app/full-name?firstName=John&lastName=Smith
# Returns: John Smith

在 Azure APIM 中,我在 API 架构中将 firstNamelastName 参数设置为“必需”。

在入站策略中,我想验证请求中是否存在两者。我发现validate-parameters 政策似乎就是这样做的:

<inbound>
    <validate-parameters specified-parameter-action="prevent"
                         unspecified-parameter-action="detect"
                         errors-variable-name="validationErrors" />
</inbound>

令我惊讶的是,这并没有解决任何问题!我必须对每个参数进行手动检查(这段代码太冗长了):

<inbound>
    <choose>
        <when condition="@( context.Request.OriginalUrl.Query.GetValueOrDefault("firstName") == null )">
            <return-response>
                <set-status code="400" reason="Bad Request" />
                <set-header name="Context-Type" exists-action="override">
                    <value>text/plain</value>
                </set-header>
                <set-body>'firstName' is required</set-body>
            </return-response>
        </when>
        <when condition="@( context.Request.OriginalUrl.Query.GetValueOrDefault("lastName") == null )">
            <return-response>
                <set-status code="400" reason="Bad Request" />
                <set-header name="Context-Type" exists-action="override">
                    <value>text/plain</value>
                </set-header>
                <set-body>'lastName' is required</set-body>
            </return-response>
        </when>
        <otherwise>
        </otherwise>
    </choose>
</inbound>

有没有更方便的方法来根据 Azure APIM 中的 API 架构验证请求?

【问题讨论】:

  • 相同的行为 - 验证不会触发 - 即使使用 api-version=2021-01-01-preview 创建 API - 我会询问产品组

标签: azure-api-management


【解决方案1】:

我们可以找到document 显示我们需要使用比2021-01-01-preview 晚的api-version 在APIM 中创建api,然后该策略才能起作用。

所以如果你在 APIM 中的 api 是过去创建的,你需要重新创建它。我检查了 Azure 门户上的 create api 操作,它已更新为使用api-version=2021-01-01-preview,如下图所示。

您也可以申请api自行创建。

【讨论】:

  • 对不起,正如我在上面已经写过的那样——这正是我所做的,但没有奏效——一定还有另一个问题
  • 请问端点 /internal-status-0123456789abcdef 正在为您报告什么 RuntimeVersion?我得到 "RuntimeVersion":"0.19.1197.0",...,"LastUpgradeStartTime":"05 May 2021 12:05"
  • 我检查了我的版本,上面写着“2021-01-01-preview”。 validate-parameters 政策目前似乎对我没有任何帮助