LoginSignup
1
1

C#でSlackの通知をWebhook経由で行う

Last updated at Posted at 2024-05-10

はじめに

C#でSlackへ通知を送りたい場合、Webhookで通知を行うのが簡単です。

SlackのWebhook登録手順について
ここではSlack App DirectoryからIncoming Webhookを登録しwebhookUrlを取得するまでの手順は省略しています。

サンプルソース

これだけでSlackに通知を送る事ができます。

メッセージ送信.cs
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

public void SendMsg(string msg)
{
    var webhookUrl = "取得したwebhookUrlを格納";
    var msgJson = new MsgJson { Text = msg };
    var json = JsonSerializer.Serialize(msgJson);
    var client = new HttpClient();
    var content = new StringContent(json, Encoding.UTF8, "application/json");
    var result = client.PostAsync(webhookUrl, content).Result;
}

public class MsgJson
{
    [JsonPropertyName("text")] public string Text { get; set; } = string.Empty;
}
1
1
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
1
1