我有以下请求数据
{
"id": "1115e297-12de-4189-8e11-75a8354f77d6",
"type": "transaction",
"version": "1.0.0",
"data": {
"account_id": "999",
"customer_info": {
"client_id": 999
},
"company_id": "999999",
"event": {
"id": 99999999,
"type_code": "3098"
}
}
}
我想编写一个忽略请求的策略,除非类型为“ transaction”且type_code为“ 3098”或“ 3099”
如果不满意,则应将请求的ID返回给调用方,而不转发请求
这是我想出的
<choose>
<when condition="@((string)context.Request.Body?.As<JObject>(true)["type"] != "transaction")">
<return-response>
<set-status code="200" reason="OK" />
<set-header name="Content-Type" exists-action="override">
<value>application/json</value>
</set-header>
<set-body>@{
var json = new JObject(
new JProperty("id", context.Request.Body?.As<JObject>(true)["id"])
);
return json.ToString();
}</set-body>
</return-response>
</when>
<when condition="@(context.Request.Body?.As<JObject>(true)["data"] == null || context.Request.Body?.As<JObject>(true)["data"]["event"] == null)">
<return-response>
<set-status code="200" reason="OK" />
<set-header name="Content-Type" exists-action="override">
<value>application/json</value>
</set-header>
<set-body>@{
var json = new JObject(
new JProperty("id", context.Request.Body?.As<JObject>(true)["id"])
);
return json.ToString();
}</set-body>
</return-response>
</when>
<when condition="@((int)context.Request.Body?.As<JObject>(true)["data"]["event"]["type_code"] != 3098 && (int)context.Request.Body?.As<JObject>(true)["data"]["event"]["type_code"] != 3099)">
<return-response>
<set-status code="200" reason="OK" />
<set-header name="Content-Type" exists-action="override">
<value>application/json</value>
</set-header>
<set-body>@{
var json = new JObject(
new JProperty("id", context.Request.Body?.As<JObject>(true)["id"])
);
return json.ToString();
}</set-body>
</return-response>
</when>
</choose>
我要给小费一个更优雅的方法吗?
答案 0 :(得分:3)
好的。如果您使用的所有return-response
策略都相同,则可以使用多行表达式:
<set-variable name="payload" value="@((string)context.Request.Body?.As<JObject>(true))" />
<choose>
<when condition="@{
var payload = (JObject)context.Variables["payload"];
if (payload?["type"] != "transaction"
|| payload?["data"]?["event"]?["type_code"] != 3099)
{
return true;
}
}">
<return-response>
<set-status code="200" reason="OK" />
<set-header name="Content-Type" exists-action="override">
<value>application/json</value>
</set-header>
<set-body>@{
var payload = (JObject)context.Variables["payload"];
var json = new JObject(
new JProperty("id", payload?["id"])
);
return json.ToString();
}</set-body>
</return-response>
</when>
</choose>