筛选响应内容Filter response content

本文介绍 Azure API 管理策略示例,该示例演示如何基于与请求关联的产品从响应有效负载中筛选数据元素。This article shows an Azure API management policy sample that demonstrates how to filter data elements from the response payload based on the product associated with the request. 若要设置或编辑策略代码,请执行设置或编辑策略中所述的步骤。To set or edit a policy code, follow the steps described in Set or edit a policy. 若要查看其他示例,请参阅策略示例To see other examples, see policy samples.

策略Policy

将代码粘贴到“出站”块中。Paste the code into the outbound block.

<!-- The policy defined in this file demonstrates how to filter data elements from the response payload based on the product associated with the request.
<!-- The snippet assumes that response content is formatted as JSON and contains root-level properties named "minutely", "hourly", "daily", "flags". -->

<!-- Use https://darksky.net/dev/ API to test this policy. -->

<!-- Copy this snippet into the outbound section. -->

<policies>
  <inbound>
    <base />
  </inbound>
  <backend>
    <base />
  </backend>
  <outbound>
    <base />
    <choose>
      <when condition="@(context.Response.StatusCode == 200 && context.Product.Name.Equals("Starter="))">
        <set-body>
          @{
            //NOTE that we are not using preserveContent=true when deserializing response body stream into a JSON object since we don't intend to access it again. See details on https://docs.azure.cn/zh-cn/api-management/api-management-transformation-policies#SetBody
            var response = context.Response.Body.As<JObject>();
            foreach (var key in new [] {"minutely", "hourly", "daily", "flags"}) {
            response.Property (key).Remove ();
           }
          return response.ToString();
          }
        </set-body>
      </when>
    </choose>    
  </outbound>
  <on-error>
    <base />
  </on-error>
</policies>

后续步骤Next steps

了解有关 APIM 策略的详细信息:Learn more about APIM policies: