0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Microsoft Azure - API Management Service: Policy を使ってリクエストを Slack へ投稿する

Posted at

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-urltemplate をつなげたものがPOST送信先のURLになります。

補足

Path の中でのパラメータ、たとえば /test/{id} の中での id を取得する場合は次のようにして値を取得できます。

context.Request.MatchedParameters["id"]

クエリパラメータは次のように取得できます。

context.Request.Url.Query.GetValueOrDefault("param_name", "default_value")

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?