APIM Azure - Get named value dynamicaly through a received variable
Asked Answered
A

1

1

I'm trying to do the following:

I have an API in APIM that receives an certain header with a key that is set in a APIM named value. For example:

http://apimSomeUrl.com/apiName/whatever request header: "country" with the value "bolivia"

through a APIM policy I want to get the value of the Named Value "bolivia" and then set as the new uri.

for example. I have a named value live "bolivia": http://google.com

When the APIM receives the request it get the header value and set it in a context variable

<set-variable name="newUrl" value="
    @{
        string [] HostNameHeader;
                
        context.Request.Headers.TryGetValue("tenant", out HostNameHeader);    

        return HostNameHeader[0];
    }
" />

Then I want to get the "newUrl" value and get the named value Bolivia, setting the request Uri with its value

I've tried this:

<set-variable name="tenant" value="
    @{
        string [] HostNameHeader;
        context.Request.Headers.TryGetValue("tenant", out HostNameHeader);    
        return HostNameHeader[0];
    }
" />

<set-header name="CustomHeader" exists-action="override">
    <value>{{@((string)context.Variables["tenant"])}}</value>
</set-header>

<!--<set-backend-service base-url="baseURLfromNamedValueComesHere" />-->

But the policy doesn't replace this {{@((string)context.Variables["tenant"])}}

it keeps writing as string enter image description here

Attired answered 10/5, 2023 at 14:46 Comment(0)
O
0

The named values are replaced when a policy must be evaluated for a request, not while it is being evaluated. So, this is not possible.

The alternative would be to simply use the choose policy and check for values of the header to set the backend service accordingly.

Another option would be to forward the request to another service (or the same APIM) with the header value in the URL path. This service (or different API on APIM) would then forward the request to the corresponding backend. This would be more generic if you don't prefer the if/else style approach of the choose policy.

Operation answered 11/5, 2023 at 2:27 Comment(2)
Hello, in the meanwhile I've found this solution. It's not what I wanted but it's a good workaround and it works ;) codit.eu/blog/…Attired
Thanks for sharing! I haven't thought about doing it that way. Really cool!Operation

© 2022 - 2024 — McMap. All rights reserved.