我正在从事API管理,后端已使用oauth客户端凭据进行了加密。如果关闭了后端,我将得到200的响应和详细错误,如下所示。
{
"error": {
"name": "StatusCodeError",
"statusCode": 404,
"message": "HTTP Error 404. The requested resource is not found.",
"options": {
"url": "https://...net.au/api/case/mycases/",
"method": "GET",
"headers": {
"Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhb....."
},
"simple": true,
"resolveWithFullResponse": false,
"transform2xxOnly": false
},
"response": {
"statusCode": 404,
"body": "HTTP Error 404. The requested resource is not found.",
"headers": {
"content-length": "315",
"content-type": "text/html; charset=us-ascii",
"server": "Microsoft-HTTPAPI/2.0 Microsoft-HTTPAPI/2.0",
"date": "Fri, 14 Jun 2019 02:12:36 GMT",
"connection": "close"
},
"request": {
"uri": {
"protocol": "https:",
"slashes": true,
"auth": null,
"host": ".....",
"port": 443,
"hostname": "....net.au",
"hash": null,
"search": null,
"query": null,
"pathname": "/api/case/mycases/",
"path": "/api/case/mycases/",
"href": "https://...."
},
"method": "GET",
"headers": {
"Authorization": "Bearer eyJ0eXAiO....."
}
}
}
},
"status": 501
}
我只想像调用api一样返回响应。并隐藏所有其他详细信息,包括访问令牌。
{
"error": {
"name": "StatusCodeError",
"statusCode": 404,
"message": "HTTP Error 404. The requested resource is not found.",
}
}
按照下面的答案,我已经更新了政策,后端处于脱机状态时会得到期望的响应,而后端处于联机状态时会得到空的响应。
<choose>
<when condition="@{
var token = context.Response.Body.As<JToken>();
if (token is JObject){
return true;
}
return false;
}">
<return-response>
<set-status code="404" reason="NotFound" />
<set-header name="Content-Type" exists-action="override">
<value>application/json</value>
</set-header>
<set-body>{
"error": {
"name": "StatusCodeError",
"statusCode": 404,
"message": "HTTP Error 404. The requested resource is not found.",
}
}</set-body>
</return-response>
</when>
</choose>
答案 0 :(得分:0)
有两种情况可以从APIM获得404响应。一种是当您尝试调用APIM不知道的API /操作时,在这种情况下,APIM会生成404响应,并且响应时间很短,就像您的第二个响应一样。
另一种情况是APIM识别API /操作,调用后端,后端以404响应。在这种情况下,APIM不会将此视为问题,而只是将后端响应中继到客户端。您在第一个示例中拥有的东西看起来像后端会回复的东西。您可以通过从Azure门户中的测试控制台进行调用并检查提供的跟踪来确认这一点。
因此,您想要做的是用您选择的一种替换404响应正文,这可以通过策略轻松完成。在任何范围内都应遵循以下原则:
<outbound>
<base/>
<choose>
<when condition="@(context.Response.StatusCode == 404)">
<return-response>
<set-status code="404" reason="NotFound">
<set-header name="Content-Type">
<value>application/json</value>
</set-header>
<set-body>{
"error": {
"name": "StatusCodeError",
"statusCode": 404,
"message": "HTTP Error 404. The requested resource is not found.",
}
}</set-body>
</return-response>
</when>
</choose>
</outbound>