重命名 Azure API 管理中出站请求中的查询参数



使用 Azure API 管理中的策略,我正在尝试重命名查询参数,但它不起作用。 如果我将复制不匹配的参数="false"更改为复制不匹配的参数="true",那么它可以工作,但行为变成了所有不匹配的参数将被传递给后端API,这将允许客户端将自己的查询参数注入到我们不想要的后端请求中。

其他一切都很好。

我想转换一个如下所示的请求:

https://{site}/search?query=dylan

自:

https://{backend-site}documents?api-version=2018-1-11&amount=1000&searchFields=Album,Artist&search=dylan

唯一不起作用的部分是将查询参数转换为命名为"search"而不是查询,而不允许从入站查询字符串传递所有参数。 我该如何解决这个问题?

<policies>
    <inbound>
        <rewrite-uri template="/" copy-unmatched-params="false" />
        <set-header name="api-key" exists-action="override">
            <value>THIS-IS-API-KEI</value>
        </set-header>
        <set-query-parameter name="api-version" exists-action="override">
            <value>2018-1-11</value>
        </set-query-parameter>
        <set-query-parameter name="amount" exists-action="override">
            <value>1000</value>
        </set-query-parameter>
        <set-query-parameter name="searchFields" exists-action="override">
            <value>Album,Artist</value>
        </set-query-parameter>
        <set-query-parameter name="search" exists-action="override">
            <value>@(context.Request.Url.Query.GetValueOrDefault("query"))</value>
        </set-query-parameter>
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

之所以从最后一个表达式中获取空值,是因为那时您的 URI 已重写为"/",并且仅设置了"api-version"、"amount"和"searchFields"查询参数。有几种方法可以做到这一点:

  1. 参考原始网址:@(context.Request.OriginalUrl.Query.GetValueOrDefault("query"))
  2. 将查询添加到操作 URI 模板 - 搜索?查询={查询} - 并从重写 URI 策略引用它:<rewrite-uri template="/?query={query}" copy-unmatched-params="false" /> 。缺点是"query"参数成为必需的,因此任何没有它的请求都将导致 404。

尝试使用变量。在开头将值分配给变量,并使用变量分配新的查询参数

您可以使用 URL 的字符串和简单的替换方法来重命名查询中的参数。在这种情况下,该参数不是必需的。

<inbound>
     <base />
     <rewrite-uri template="@{
        return "/some-url-here-or-your-previously-constructed-url" + context.Request.OriginalUrl.QueryString
            .Replace("old-name", "new-name");
         }" copy-unmatched-params="false" />
 </inbound>

最新更新