【问题标题】:Azure API Management Service Set body Policy - modify JSON response to return certain fieldsAzure API 管理服务设置正文策略 - 修改 JSON 响应以返回某些字段
【发布时间】:2017-11-22 10:08:08
【问题描述】:

基于

Azure API Management Service "Set body" Policy

我们可以修改 API 服务的响应。例如,而不是在下面返回:

{ 
  "company" : "Azure",
  "service" : "API Management"
}

我们只想退货:

{ "company" : "Azure" }

我不知道如何做到这一点,因为我不知道他们在他们的文档中使用了什么样的编程语言/语法,如下所示:

<set-body>  
@{   
    string inBody = context.Request.Body.As<string>(preserveContent: true);   
    if (inBody[0] =='c') {   
        inBody[0] = 'm';   
    }   
    return inBody;   
}  
</set-body>  

【问题讨论】:

  • 我相信它的 c#,我的意思是,它看起来和感觉都像它

标签: azure azure-api-management


【解决方案1】:

您看到的内容称为Policy expressions,并在official documentation here 上有详细描述。该网站的简短引述如下:

策略表达式语法为 C# 6.0。每个表达式都可以访问 隐式提供的上下文变量和允许的 .NET 子集 框架类型。

set-bodysamples 中更合适的样本将是过滤输出的样本:

<!-- Copy this snippet into the outbound section to remove a number of data elements from the response received from the backend service based on the name of the api product -->  
    <set-body>@{  
        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>  

要为您的特定对象自定义 - 您要删除 service 属性:

    <set-body>@{  
        var response = context.Response.Body.As<JObject>();  
        foreach (var key in new [] {"service"}) {  
          response.Property (key).Remove ();  
        }  
        return response.ToString();  
      }  
    </set-body>  

【讨论】:

  • @(context.Request.Body.As(preserveContent: true)) 我的入站请求中有这个。我只想在数据中,如果存在另一个组合,我想拒绝请求。如何做到这一点
  • @astaykov 我尝试在文档中使用它,但在我的情况下它返回一个 http 500,说“表达式评估失败。'UTF8' 不是有效的编码名称\r\n 在 Microsoft .WindowsAzure.ApiManagement.Proxy.Gateway.PipelineMessage.GetEncoding(Encoding defaultValue)\r\n at Microsoft.WindowsAzure.ApiManagement.Proxy.Gateway.MessageBody.As[T](Boolean preserveContent)", null, "'UTF8' is无效的编码名称”
猜你喜欢
  • 2023-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-24
  • 2020-06-11
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多