如何在 Azure API 管理中为查询字符串参数指定重写 url

问题描述 投票:0回答:3

我正在使用 Azure API 管理将传入的查询字符串转换为另一个查询字符串。

我的转换代码是:

<policies>
    <inbound>
        <rewrite-uri template="api/primes?a={a}&b={b}" />
        <base />
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

当我尝试保存编辑时,出现错误:

One or more fields contain incorrect values: 
'=' is an unexpected token. The expected token is ';'. Line 15, position 50.

指的是

a={a}
中的等号。如何修正
rewrite-uri
的模板?输入网址例如为
https://example.com/sum?a=7&b=5

azure azure-api-management
3个回答
10
投票

尝试更换:

<rewrite-uri template="api/primes?a={a}&b={b}" />

与:

<rewrite-uri template="api/primes?a={a}&amp;b={b}" />

欲了解更多详细信息,请访问 https://azure.microsoft.com/en-us/blog/policy-expressions-in-azure-api-management/


0
投票

您只需要在APIM中创建“查询参数”而不是“模板参数”。 然后您的重写 uri 不需要包含查询参数,因为一旦通过入站提供,APIM 就会自动将其添加到后端 url。

<rewrite-uri template="api/primes" />

如果请求 URL 是这样的:

https://example.com/sum?a=7&b=5

那么发送到后端的HTTP请求将是这样的:

GET backendapi/api/primes?a=7&b=5

如果请求 URL 没有这样的查询字符串:

https://example.com/sum

那么发送到后端的 HTTP 请求就简单如下:

GET backendapi/api/primes

0
投票

在我的例子中,传入的查询参数由 APIM 进行编码,因此我必须执行以下操作才能获得 1:1:

<inbound>
    <base />
    <set-variable name="queryDecoded" value="@(System.Net.WebUtility.UrlDecode(context.Request.Url.QueryString))" />
    <rewrite-uri template="@{
        var queryDecoded = (string)context.Variables["queryDecoded"];
        var uri = "/path" + queryDecoded;
        return uri;        
    }" copy-unmatched-params="false" />
</inbound>
© www.soinside.com 2019 - 2024. All rights reserved.