Setting Backend Response Status Code in Azure APIM Policy

151 views Asked by At

I have the following Azure APIM policy. However, the new JProperty("status", context.Response.StatusCode) is not being set correctly. I suspect it is because the context.Response.StatusCode is not available in this context. Any suggestions on how I can fix this so that the correct status code of the response is set?

<policies>
    <inbound>
    </inbound>
    <backend>
        <forward-request />
    </backend>
    <outbound>
        <send-one-way-request mode="new" timeout="10000">
            <set-url>myURL</set-url>
            <set-method>POST</set-method>
            <set-body>@{
            var appIdNumber = Convert.ToInt32(context.Variables["appId"]);
            var apiId = context.Variables["apiId"];
                        JArray jarrayObj = new JArray();
                            JObject obj = new JObject(
                                new JProperty("apiId", apiId),
                                new JProperty("appId", appIdNumber),
                                new JProperty("endpoint", context.Request.Url.Path + context.Request.Url.QueryString),
                                new JProperty("method", context.Request.Method),
                                new JProperty("status", context.Response.StatusCode),
                                new JProperty("apiLatency", context.Elapsed.Milliseconds),
                                new JProperty("timestamp", new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds()),
                                new JProperty("originIp", context.Request.IpAddress)
                                );
                            jarrayObj.Add(obj);
                        return jarrayObj.ToString();
                    }</set-body>
        </send-one-way-request>
    </outbound>
    <on-error />
</policies>

I suspect it is because the context.Response.StatusCode is not available in this context.

1

There are 1 answers

0
James De Luca On

I did figure this out. Since I was mocking this endpoint, the status code was not being set. I added this line to the Backend Policy, and the status code is now set correctly.

<backend>
        <set-status code="200" reason="OK" />
</backend>