azureazure-api-managementazure-policy

Unable to remove backslash from json response in azure APIM policy


While adding a inbound and backend policy in Azure APIM i am facing issue with json parsing

<policies>
    <inbound>
        <set-header name="Content-Type" exists-action="override">
            <value>application/json</value>
        </set-header>
        <set-variable name="originalRequestBody" value="@{
            return context.Request.Body.As<JObject>(preserveContent: true);
        }" />
        <set-backend-service base-url="https://api-qa.integrator.bnksvc.com/berpContractService/api/v1/" />
    </inbound>
    <backend>
        <send-request mode="new" response-variable-name="backendResponse">
            <set-url>@("https://xxx-xx.xxx.xxx.com/berpContractService/api/v1/processcontracts")</set-url>
            <set-method>POST</set-method>
            <set-body>@{
                var originalBody = (JObject)context.Variables["originalRequestBody"];
                string jsonString = originalBody.ToString(Newtonsoft.Json.Formatting.None);
                jsonString = jsonString.Replace(@"\", string.Empty);
                return jsonString;
            }</set-body>
        </send-request>
    </backend>
    <outbound>
        <base />
        <return-response response-variable-name="backendResponse" />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

{\"requestid\":\"0d8db8ec-f878-4954-a07a-2d086qqq\",\"contract\":\"avasacs\"}

My json from inbound body is getting converted and backshlash is added. I want to remove these backslashes before sending json to backend


Solution

  • Try to move the set-header block to set the Content-Type within the backend section. This ensures that the content type is set correctly for the backend request.

    <backend>
        <send-request mode="new" response-variable-name="backendResponse">
            <set-url>@("https://xxx-xx.xxx.xxx.com/berpContractService/api/v1/processcontracts")</set-url>
            <set-method>POST</set-method>
            <set-body>@{
                var originalBody = (JObject)context.Variables["originalRequestBody"];
                string jsonString = originalBody.ToString(Newtonsoft.Json.Formatting.None);
                jsonString = jsonString.Replace(@"\", string.Empty);
                return jsonString;
            }</set-body>
            <set-header name="Content-Type" exists-action="override">
                <value>application/json</value>
            </set-header>
        </send-request>
    </backend>