首页 > 解决方案 > 在 Azure APIM 中验证请求参数

问题描述

我定义了一个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 架构的请求?

标签: azure-api-management

解决方案


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

在此处输入图像描述

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

在此处输入图像描述

您也可以请求api自己创建它。


推荐阅读