Search code examples
c#azureazure-api-managementazure-policyapim

Set body in Azure APIM Policy


My incoming payload is

{ "data":"testdata"}

along with a header X-Type = headerType, I want to map the header into the payload before sending it to the backend system

I want to convert the payload as below

{"data":"testdata","type":"headerType"}

I tried set body but no luck, can some one help

<set-body>@{ 
    var requestBody = context.Request.Body.As<JObject>(preserveContent: 
    true);

    requestBody ["type"] = context.Request.Headers.GetValueOrDefault("X-Type","");

    return requestBody.ToString();
}</set-body>

Solution

  • I'm not able to reproduce your issue.

    Maybe it's a typo in question or there's really a space in this line: requestBody ["type"] =

    Please do not forget to send the header.

    For testing purposes, the set-body policy is placed inside a return-response policy:

    Inbound policy:

    <inbound>
        <base />
        <return-response>
            <set-status code="200" reason="ok" />
            <set-header name="Content-Type" exists-action="override">
                <value>application/json</value>
            </set-header>
            <set-body>@{
                var requestBody  = context.Request.Body.As<JObject>(true);
                requestBody["type"] = context.Request.Headers.GetValueOrDefault("X-Type","");
                return requestBody.ToString();               
            }</set-body>
        </return-response>
    </inbound>
    

    Test in API Management with

    • header X-Type : lorem
    • request body: { "data":"testdata"}

    enter image description here