ΩmegaMan
ΩmegaMan

Reputation: 31721

Policy rewrite-uri To Append Context Variable in Azure APIM

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."
>     ] }

Upvotes: 10

Views: 18892

Answers (3)

Jayen Chondigara
Jayen Chondigara

Reputation: 495

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"]}")" />

Upvotes: 3

Evandro de Paula
Evandro de Paula

Reputation: 2642

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.

Upvotes: 16

ΩmegaMan
ΩmegaMan

Reputation: 31721

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

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

Upvotes: 3

Related Questions