Communityライティング&編集github.com

Azure Event Grid .NET SDK

Azure Event Grid の .NET クライアントライブラリ。イベント駆動型アーキテクチャ、pub/sub メッセージング、CloudEvents、EventGridEvents のためのイベントの発行と消費を行います。

Azure Event Grid .NET SDK とは?

Azure.Messaging.EventGrid (.NET) は、Azure Event Grid のトピック、ドメイン、名前空間にイベントを発行するための公式 .NET クライアントライブラリです。このスキルは、EventGridPublisherClient を使用したプッシュ配信(トピック/ドメイン)と、EventGridSenderClient および EventGridReceiverClient を使用したプル配信(名前空間)の両方をサポートします。Azure Functions トリガーとの統合も含まれており、EventGridEvent(Azure 独自スキーマ)と CloudEvent(CNCF 標準スキーマ)の両方の形式でイベントを発行、解析、消費できます。API キー、Microsoft Entra ID(マネージド ID を含む)、SAS トークンによる認証をサポートし、最適なプラクティスとして CloudEvents の使用、バッチイベント処理、Entra ID 認証の優先、べき等ハンドラーの実装、デッドレター設定などを推奨しています。エラーハンドリングやフェイルオーバーパターンのコード例も提供されており、堅牢なイベント駆動型アプリケーションの構築を支援します。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/microsoft/agent-skills/tree/main/.github/plugins/azure-sdk-dotnet/skills/azure-eventgrid-dotnet

Installed? Explore more ライティング&編集 skills: steipete/notion, langchain-ai/langchain, bytedance/podcast-generation · View all 6 →

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

Azure.Messaging.EventGrid (.NET)

Azure Event Grid のトピック、ドメイン、名前空間にイベントを発行するためのクライアントライブラリ。

インストール

# トピックおよびドメイン向け(プッシュ配信)
dotnet add package Azure.Messaging.EventGrid

# 名前空間向け(プル配信)
dotnet add package Azure.Messaging.EventGrid.Namespaces

# CloudNative CloudEvents の相互運用のため
dotnet add package Microsoft.Azure.Messaging.EventGrid.CloudNativeCloudEvents

現在のバージョン: 4.28.0(安定版)

環境変数

EVENT_GRID_TOPIC_ENDPOINT=https://<topic-name>.<region>.eventgrid.azure.net/api/events  # 必須: Event Grid トピックまたはドメインのエンドポイント
EVENT_GRID_TOPIC_KEY=<access-key>  # AzureKeyCredential 認証の場合のみ必須
EVENT_GRID_NAMESPACE_ENDPOINT=https://<namespace>.<region>.eventgrid.azure.net  # オプション: Event Grid 名前空間エンドポイント
EVENT_GRID_TOPIC_NAME=<topic-name>  # 必須: Event Grid トピック名
EVENT_GRID_SUBSCRIPTION_NAME=<subscription-name>  # オプション: Event Grid サブスクリプション名
AZURE_TOKEN_CREDENTIALS=prod  # 本番環境で DefaultAzureCredential を使用する場合のみ必須

クライアント階層

プッシュ配信(トピック/ドメイン)
└── EventGridPublisherClient
    ├── SendEventAsync(EventGridEvent)
    ├── SendEventsAsync(IEnumerable<EventGridEvent>)
    ├── SendEventAsync(CloudEvent)
    └── SendEventsAsync(IEnumerable<CloudEvent>)

プル配信(名前空間)
├── EventGridSenderClient
│   └── SendAsync(CloudEvent)
└── EventGridReceiverClient
    ├── ReceiveAsync()
    ├── AcknowledgeAsync()
    ├── ReleaseAsync()
    └── RejectAsync()

認証

API キー認証

using Azure;
using Azure.Messaging.EventGrid;

EventGridPublisherClient client = new(
    new Uri("https://mytopic.eastus-1.eventgrid.azure.net/api/events"),
    new AzureKeyCredential("<access-key>"));

Microsoft Entra トークン資格情報

using Azure.Identity;
using Azure.Messaging.EventGrid;

// ローカル開発: DefaultAzureCredential。本番環境: AZURE_TOKEN_CREDENTIALS=prod または AZURE_TOKEN_CREDENTIALS=<specific_credential> を設定
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// または本番環境では特定の資格情報を直接使用:
// 参照: https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();
EventGridPublisherClient client = new(
    new Uri("https://mytopic.eastus-1.eventgrid.azure.net/api/events"),
    credential);

SAS トークン認証

string sasToken = EventGridPublisherClient.BuildSharedAccessSignature(
    new Uri(topicEndpoint),
    DateTimeOffset.UtcNow.AddHours(1),
    new AzureKeyCredential(topicKey));

var sasCredential = new AzureSasCredential(sasToken);
EventGridPublisherClient client = new(
    new Uri(topicEndpoint),
    sasCredential);

イベントの発行

EventGridEvent スキーマ

EventGridPublisherClient client = new(
    new Uri(topicEndpoint),
    new AzureKeyCredential(topicKey));

// 単一イベント
EventGridEvent egEvent = new(
    subject: "orders/12345",
    eventType: "Order.Created",
    dataVersion: "1.0",
    data: new { OrderId = "12345", Amount = 99.99 });

await client.SendEventAsync(egEvent);

// イベントのバッチ
List<EventGridEvent> events = new()
{
    new EventGridEvent(
        subject: "orders/12345",
        eventType: "Order.Created",
        dataVersion: "1.0",
        data: new OrderData { OrderId = "12345", Amount = 99.99 }),
    new EventGridEvent(
        subject: "orders/12346",
        eventType: "Order.Created",
        dataVersion: "1.0",
        data: new OrderData { OrderId = "12346", Amount = 149.99 })
};

await client.SendEventsAsync(events);

CloudEvent スキーマ

CloudEvent cloudEvent = new(
    source: "/orders/system",
    type: "Order.Created",
    data: new { OrderId = "12345", Amount = 99.99 });

cloudEvent.Subject = "orders/12345";
cloudEvent.Id = Guid.NewGuid().ToString();
cloudEvent.Time = DateTimeOffset.UtcNow;

await client.SendEventAsync(cloudEvent);

// CloudEvents のバッチ
List<CloudEvent> cloudEvents = new()
{
    new CloudEvent("/orders", "Order.Created", new { OrderId = "1" }),
    new CloudEvent("/orders", "Order.Updated", new { OrderId = "2" })
};

await client.SendEventsAsync(cloudEvents);

Event Grid ドメインへの発行

// イベントはドメインルーティングのために Topic プロパティを指定する必要があります
List<EventGridEvent> events = new()
{
    new EventGridEvent(
        subject: "orders/12345",
        eventType: "Order.Created",
        dataVersion: "1.0",
        data: new { OrderId = "12345" })
    {
        Topic = "orders-topic"  // ドメイントピック名
    },
    new EventGridEvent(
        subject: "inventory/item-1",
        eventType: "Inventory.Updated",
        dataVersion: "1.0",
        data: new { ItemId = "item-1" })
    {
        Topic = "inventory-topic"
    }
};

await client.SendEventsAsync(events);

カスタムシリアル化

using System.Text.Json;

var serializerOptions = new JsonSerializerOptions
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};

var customSerializer = new JsonObjectSerializer(serializerOptions);

EventGridEvent egEvent = new(
    subject: "orders/12345",
    eventType: "Order.Created",
    dataVersion: "1.0",
    data: customSerializer.Serialize(new OrderData { OrderId = "12345" }));

await client.SendEventAsync(egEvent);

プル配信(名前空間)

名前空間トピックへのイベント送信

using Azure;
using Azure.Messaging;
using Azure.Messaging.EventGrid.Namespaces;

var senderClient = new EventGridSenderClient(
    new Uri(namespaceEndpoint),
    topicName,
    new AzureKeyCredential(topicKey));

// 単一イベントの送信
CloudEvent cloudEvent = new("employee_source", "Employee.Created", 
    new { Name = "John", Age = 30 });
await senderClient.SendAsync(cloudEvent);

// バッチ送信
await senderClient.SendAsync(new[]
{
    new CloudEvent("source", "type", new { Name = "Alice" }),
    new CloudEvent("source", "type", new { Name = "Bob" })
});

イベントの受信と処理

var receiverClient = new EventGridReceiverClient(
    new Uri(namespaceEndpoint),
    topicName,
    subscriptionName,
    new AzureKeyCredential(topicKey));

// イベントの受信
ReceiveResult result = await receiverClient.ReceiveAsync(maxEvents: 10);

List<string> lockTokensToAck = new();
List<string> lockTokensToRelease = new();

foreach (ReceiveDetails detail in result.Details)
{
    CloudEvent cloudEvent = detail.Event;
    string lockToken = detail.BrokerProperties.LockToken;
    
    try
    {
        // イベントの処理
        Console.WriteLine($"イベント: {cloudEvent.Type}, データ: {cloudEvent.Data}");
        lockTokensToAck.Add(lockToken);
    }
    catch (Exception)
    {
        // 再試行のために解放
        lockTokensToRelease.Add(lockToken);
    }
}

// 正常に処理されたイベントを確認
if (lockTokensToAck.Any())
{
    await receiverClient.AcknowledgeAsync(lockTokensToAck);
}

// 再試行のためにイベントを解放
if (lockTokensToRelease.Any())
{
    await receiverClient.ReleaseAsync(lockTokensToRelease);
}

イベントの拒否(デッドレター)

// 処理できないイベントを拒否
await receiverClient.RejectAsync(new[] { lockToken });

イベントの消費(Azure Functions)

EventGridEvent トリガー

using Azure.Messaging.EventGrid;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.EventGrid;

public static class EventGridFunction
{
    [FunctionName("ProcessEventGridEvent")]
    public static void Run(
        [EventGridTrigger] EventGridEvent eventGridEvent,
        ILogger log)
    {
        log.LogInformation($"イベントタイプ: {eventGridEvent.EventType}");
        log.LogInformation($"サブジェクト: {eventGridEvent.Subject}");
        log.LogInformation($"データ: {eventGridEvent.Data}");
    }
}

CloudEvent トリガー

using Azure.Messaging;
using Microsoft.Azure.Functions.Worker;

public class CloudEventFunction
{
    [Function("ProcessCloudEvent")]
    public void Run(
        [EventGridTrigger] CloudEvent cloudEvent,
        FunctionContext context)
    {
        var logger = context.GetLogger("ProcessCloudEvent");
        logger.LogInformation($"イベントタイプ: {cloudEvent.Type}");
        logger.LogInformation($"ソース: {cloudEvent.Source}");
        logger.LogInformation($"データ: {cloudEvent.Data}");
    }
}

イベントの解析

EventGridEvent の解析

// JSON 文字列から
string json = "..."; // Event Grid webhook ペイロード
EventGridEvent[] events = EventGridEvent.ParseMany(BinaryData.FromString(json));

foreach (EventGridEvent egEvent in events)
{
    if (egEvent.TryGetSystemEventData(out object systemEvent))
    {
        // システムイベントの処理
        switch (systemEvent)
        {
            case StorageBlobCreatedEventData blobCreated:
                Console.WriteLine($"Blob が作成されました: {blobCreated.Url}");
                break;
        }
    }
    else
    {
        // カスタムイベントの処理
        var customData = egEvent.Data.ToObjectFromJson<MyCustomData>();
    }
}

CloudEvent の解析

CloudEvent[] cloudEvents = CloudEvent.ParseMany(BinaryData.FromString(json));

foreach (CloudEvent cloudEvent in cloudEvents)
{
    var data = cloudEvent.Data.ToObjectFromJson<MyEventData>();
    Console.WriteLine($"タイプ: {cloudEvent.Type}, データ: {data}");
}

システムイベント

// 一般的なシステムイベントタイプ
using Azure.Messaging.EventGrid.SystemEvents;

// ストレージイベント
StorageBlobCreatedEventData blobCreated;
StorageBlobDeletedEventData blobDeleted;

// リソースイベント
ResourceWriteSuccessEventData resourceCreated;
ResourceDeleteSuccessEventData resourceDeleted;

// App Service イベント
WebAppUpdatedEventData webAppUpdated;

// Container Registry イベント
ContainerRegistryImagePushedEventData imagePushed;

// IoT Hub イベント
IotHubDeviceCreatedEventData deviceCreated;

主要な型のリファレンス

型目的
EventGridPublisherClientトピック/ドメインへの発行
EventGridSenderClient名前空間トピックへの送信
EventGridReceiverClient名前空間サブスクリプションからの受信
EventGridEventEvent Grid ネイティブスキーマ
CloudEventCloudEvents 1.0 スキーマ
ReceiveResultプル配信の応答
ReceiveDetailsブローカープロパティを持つイベント
BrokerPropertiesロックトークン、配信カウント

イベントスキーマの比較

機能EventGridEventCloudEvent
標準Azure 固有CNCF 標準
必須フィールドsubject, eventType, dataVersion, datasource, type
拡張性制限あり拡張属性
相互運用性Azure のみクロスプラットフォーム

ベストプラクティス

  1. CloudEvents を使用する — 新しい実装では CloudEvents を推奨(業界標準)
  2. イベントをバッチ処理する — 効率化のために複数イベントを1回の呼び出しで送信
  3. Entra ID を使用する — アクセスキーよりもマネージド ID を優先
  4. べき等ハンドラー — イベントは複数回配信される可能性がある
  5. イベント TTL を設定する — 名前空間イベントの有効期限を構成
  6. 部分的な障害を処理する — イベントを個別に確認/解放
  7. デッドレターを使用する — 失敗したイベントのためにデッドレターを設定
  8. スキーマを検証する — 処理前にイベントデータを検証

エラーハンドリング

using Azure;

try
{
    await client.SendEventAsync(cloudEvent);
}
catch (RequestFailedException ex) when (ex.Status == 401)
{
    Console.WriteLine("認証に失敗しました - 資格情報を確認してください");
}
catch (RequestFailedException ex) when (ex.Status == 403)
{
    Console.WriteLine("認可に失敗しました - RBAC 権限を確認してください");
}
catch (RequestFailedException ex) when (ex.Status == 413)
{
    Console.WriteLine("ペイロードが大きすぎます - イベントあたり最大 1MB、バッチ合計 1MB");
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"Event Grid エラー: {ex.Status} - {ex.Message}");
}

フェイルオーバーパターン

try
{
    var primaryClient = new EventGridPublisherClient(primaryUri, primaryKey);
    await primaryClient.SendEventsAsync(events);
}
catch (RequestFailedException)
{
    // セカンダリリージョンにフェイルオーバー
    var secondaryClient = new EventGridPublisherClient(secondaryUri, secondaryKey);
    await secondaryClient.SendEventsAsync(events);
}

関連 SDK

SDK目的インストール
Azure.Messaging.EventGridトピック/ドメイン(この SDK)dotnet add package Azure.Messaging.EventGrid
Azure.Messaging.EventGrid.Namespacesプル配信dotnet add package Azure.Messaging.EventGrid.Namespaces
Azure.Identity認証dotnet add package Azure.Identity
Microsoft.Azure.WebJobs.Extensions.EventGridAzure Functions トリガーdotnet add package Microsoft.Azure.WebJobs.Extensions.EventGrid

参考リンク

リソースURL
NuGet パッケージhttps://www.nuget.org/packages/Azure.Messaging.EventGrid
API リファレンスhttps://learn.microsoft.com/dotnet/api/azure.messaging.eventgrid
クイックスタートhttps://learn.microsoft.com/azure/event-grid/custom-event-quickstart
プル配信https://learn.microsoft.com/azure/event-grid/pull-delivery-overview
GitHub ソースhttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/eventgrid/Azure.Messaging.EventGrid

Individual skills in this repo

This repo contains 12 individual skills — each has its own dedicated page.

microsoft/azure-ai-agents-persistent-dotnet

Azure AI Agents Persistent SDK for .NET. Low-level SDK for creating and managing AI agents with threads, messages, runs, and tools. Use for agent CRUD, conversation threads, streaming responses, function calling, file search, and code interpreter. Triggers: "PersistentAgentsClient", "persistent agents", "agent threads", "agent runs", "streaming agents", "function calling agents .NET".

microsoft/azure-ai-document-intelligence-dotnet

Azure AI Document Intelligence SDK for .NET. Extract text, tables, and structured data from documents using prebuilt and custom models. Use for invoice processing, receipt extraction, ID document analysis, and custom document models. Triggers: "Document Intelligence", "DocumentIntelligenceClient", "form recognizer", "invoice extraction", "receipt OCR", "document analysis .NET".

microsoft/azure-ai-openai-dotnet

Azure OpenAI SDK for .NET. Client library for Azure OpenAI and OpenAI services. Use for chat completions, embeddings, image generation, audio transcription, and assistants. Triggers: "Azure OpenAI", "AzureOpenAIClient", "ChatClient", "chat completions .NET", "GPT-4", "embeddings", "DALL-E", "Whisper", "OpenAI .NET".

microsoft/azure-ai-projects-dotnet

Azure AI Projects SDK for .NET. High-level client for Azure AI Foundry projects including agents, connections, datasets, deployments, evaluations, and indexes. Use for AI Foundry project management, versioned agents, and orchestration. Triggers: "AI Projects", "AIProjectClient", "Foundry project", "versioned agents", "evaluations", "datasets", "connections", "deployments .NET".

microsoft/azure-ai-voicelive-dotnet

Azure AI Voice Live SDK for .NET. Build real-time voice AI applications with bidirectional WebSocket communication. Use for voice assistants, conversational AI, real-time speech-to-speech, and voice-enabled chatbots. Triggers: "voice live", "real-time voice", "VoiceLiveClient", "VoiceLiveSession", "voice assistant .NET", "bidirectional audio", "speech-to-speech".

microsoft/azure-eventhub-dotnet

Azure Event Hubs SDK for .NET. Use for high-throughput event streaming: sending events (EventHubProducerClient, EventHubBufferedProducerClient), receiving events (EventProcessorClient with checkpointing), partition management, and real-time data ingestion. Triggers: "Event Hubs", "event streaming", "EventHubProducerClient", "EventProcessorClient", "send events", "receive events", "checkpointing", "partition".

microsoft/azure-identity-dotnet

Azure Identity library for .NET. Authentication library for Azure SDK clients using Microsoft Entra ID. Use for DefaultAzureCredential, managed identity, service principals, and developer credentials. Triggers: "Azure Identity", "DefaultAzureCredential", "ManagedIdentityCredential", "ClientSecretCredential", "authentication .NET", "Azure auth", "credential chain".

microsoft/azure-kusto-graph

Build and query Kusto graphs from natural language. Covers transient graphs (make-graph), persistent graph models/snapshots, pattern matching (graph-match), shortest paths, connected components, and graph-to-table export. Generates the edges-first thinking: define edges, define node lookups, union, make-graph. WHEN: make-graph, graph-match, graph-shortest-paths, graph-to-table, graph-mark-components, persistent graph, graph model, graph snapshot, build a graph from data, find paths between nodes, pattern matching in graph, connected components, transient graph, Kusto graph, KQL graph.

microsoft/azure-kusto-irql

Compose IRQL (Incident Response Query Language) queries for Kusto cybersecurity investigations. Translates natural language hunting questions into composable IRQL pipelines using Get_*, Extract_*, and Enrich_* functions. WHEN: IRQL query, security hunt, threat hunting KQL, incident response query, compose hunting pipeline, failed logins, phishing investigation, lateral movement, process execution, file creation events.

microsoft/azure-kusto-irql-graph

Apply IRQL graph functions to KQL or IRQL query results for Kusto Explorer visualization. Generates Lift_To_Graph mappings and composes Graph_Render_View, Graph_Fold_By_Property, Extract_Node_*, Enrich_Node_*, and Enrich_Graph_* calls. Accepts a supplied query or limited basic natural-language source request; it is not a general natural-language-to-KQL/IRQL skill. WHEN: Lift_To_Graph, Graph_Render_View, Graph_Fold_By_Property, IRQL graph enrichment, graph mapping for existing query results, icon-decorated graph, fold graph nodes. Use azure-kusto-graph for native make-graph analysis, graph-match, shortest paths, components, or persistent graphs.

microsoft/azure-local

Plan, deploy, operate, and troubleshoot Azure Local (formerly Azure Stack HCI): sizing and prerequisites, Arc registration, lifecycle updates, workloads (Azure Local VMs, AKS on Azure Local, images, disks, logical networks), SDN and network security, and failure triage — starting read-only and confirming before risky changes. WHEN: Azure Local, Azure Stack HCI, Arc resource bridge, custom location, Azure Local VM, Arc VM, AKS on Azure Local, AKS hybrid, SDN, Lifecycle Manager, Azure Local update, disconnected site.

microsoft/azure-local-multi-rack

Plan, deploy, operate, and troubleshoot multi-rack (rack scale) deployments of Azure Local — preintegrated racks scaling to hundreds of machines, built on Network Fabric Controller, Cluster Manager, SAN storage, and managed network fabric. Use for the Microsoft.NetworkCloud and Microsoft.ManagedNetworkFabric control plane. NOT for standard 1-16 node Azure Local, and NOT for rack-aware clusters (two racks as availability zones, up to 8 nodes, synchronous replication) — those are standard scale. WHEN: multi-rack, rack scale Azure Local, aggregation rack, compute rack, Network Fabric Controller, NFC, Cluster Manager, network fabric, isolation domain, az networkcloud, az networkfabric, multi-rack logical network, multi-rack Arc VM.

関連スキル