Reputation: 215
I am a newbie with azure APIM. I am trying to implement such a functionality where I need to make sure that when the client sends the request with the proper subscription-key and wants to add a custom header to route to the appropriate backend service URL. Without adding a Web Service URL only API URL Suffix I have. Otherwise, I have to create 10 same apis with little changes in the URL.
The client adds the custom header in his request to base URL https://my-app-api.azure-api.net/api/customers
Ocp-Apim-Subscription-Key: Keys-for-auth
"X-subjectName": my-subject-value
When the request came to the backend to override the URI with that header, I need to extract the custom header from the call and override the backend URI. Can I do it via policies?
After overriding my backend URI it should look like this: https://my.api.com/api/v1/my-subject-value /customers
Thank you!
Policy from the comments:
<inbound>
<set-variable name="myvar" value="@(context.Request.Headers.GetValueOrDefault("my-header",""))" />
<set-backend-service base-url="my-api-backend.com{{myvar}}" />
</inbound>
Upvotes: 1
Views: 3535
Reputation: 3967
Please get the value of the variable this way:
context.Variables.GetValueOrDefault<string>("myvar")
With the rewrite-uri the value of the variable can be appended to URL:
<inbound>
<set-variable name="myvar" value="@(context.Request.Headers.GetValueOrDefault("my-header",""))" />
<set-backend-service base-url="my-api-backend.com" />
<rewrite-uri template="@("/" + context.Variables.GetValueOrDefault<string>("myvar"))" copy-unmatched-params="false" />
</inbound>
Please find below a complete working example for demonstration:
<policies>
<inbound>
<base />
<set-variable name="myvar" value="@(context.Request.Headers.GetValueOrDefault("my-header",""))" />
<rewrite-uri template="@("/?name=" + context.Variables.GetValueOrDefault<string>("myvar"))" copy-unmatched-params="false" />
<set-backend-service base-url="https://api.agify.io" />
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
</outbound>
<on-error>
<base />
</on-error>
</policies>
Request with custom header:
Result from trace:
Upvotes: 2