Policy rewrite-uri To Append Context Variable in Azure APIM
Asked Answered
J

3

10

What is the approach to a simple append to the url of a context variable such as context.Variables["accountKey"] during a policy rewrite?

The end result should be /accounts/232.

I have success earlier in setting it

set-variable (0.003 ms)
{
    "message": "Context variable was successfully set.",
    "name": "accountKey",
    "value": "232"
}

One of the things tried:

<policies>
    <inbound>
        <base />
        <rewrite-uri template="/accounts/{accountKey}" />
    </inbound>

But I get this error

> Error Receive
>     rewrite-uri (0.260 ms) {
>     "messages": [
>         null,
>         "Variable accountKey has no value.",
>         "Variable accountKey has no value."
>     ] }
Jeana answered 18/5, 2018 at 16:20 Comment(0)
L
16

Configure the inbound rule in the policy as follows:

<inbound>
    <base />
    <set-variable name="accountKey" value="232" />
    <rewrite-uri template="@{
        return "/account/" + context.Variables.GetValueOrDefault<string>("accountKey");
    }"/>
</inbound>

{} in rewrite-uri are for query string parameters in the original request URL.

Find more details about rewrite-uri section in the Microsoft docs at Rewrite URL - API Management transformation policies.

Leucite answered 18/5, 2018 at 21:41 Comment(0)
J
3

I ended up using this call as shown as an alternative:

<rewrite-uri template="@($"/account/{(string)context.Variables["accountKey"]}/")" />

Jeana answered 24/5, 2018 at 20:15 Comment(0)
D
3

In my case, my URL was

https://test.com/send/

I need to add query string from context variable name (name = myName)

https://test.com/send/myName

This is working for me:

<rewrite-uri template="@($"{(string)context.Variables["name"]}")" />
Douty answered 15/10, 2020 at 11:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.