Microsoft Azure の API Management Service で、 API Management Service に来た POST リクエスト (Content-Type: "application/json") を Slack へ投稿する場合の Policy を紹介します。
Slack への投稿には Incoming WebHook を使うものとします。
サンプル
inbound の記述を追加します。
<policies>
<inbound>
<base />
<set-body template="none">@{
JObject inBody = context.Request.Body.As<JObject>();
string message = JsonConvert.SerializeObject(inBody, Newtonsoft.Json.Formatting.Indented);
JObject jObject = new JObject();
jObject["channel"] = "#channel_name";
jObject["icon_emoji"] = ":ghost:";
jObject["text"] = "```\n" + message + "\n```";
jObject["username"] = "Something";
return jObject.ToString();
}</set-body>
<rewrite-uri template="/xxxxxxxxxxxxxxxxx" copy-unmatched-params="false" />
<set-backend-service base-url="https://hooks.slack.com/services/xxxxxxxxxxxxxxxxxxxxxx" />
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
</outbound>
<on-error>
<base />
</on-error>
</policies>
set-body
の中で、 body の変換を行います。 ここでは もともとのリクエストがJSONということにしていますが、 context.Request.Body.AsFormUrlEncodedContent()
を使うとフォームのデータも取得できます。
JsonConvert.SerializeObject(inBody, Newtonsoft.Json.Formatting.Indented)
は、リクエストのボディにあるJSONを読みやすい形にフォーマットしています。
改めてJSONの文字列を作成するため、 jObject
を生成して新しいJSONを作成します。 最後には、 ToString()
で文字列への変換が必要です。
rewrite-url
, set-backend-service
で Slack の WebHook のURLを設定しています。 base-url
と template
をつなげたものがPOST送信先のURLになります。
補足
Path の中でのパラメータ、たとえば /test/{id}
の中での id
を取得する場合は次のようにして値を取得できます。
context.Request.MatchedParameters["id"]
クエリパラメータは次のように取得できます。
context.Request.Url.Query.GetValueOrDefault("param_name", "default_value")