azure-eventgrid-dotnet
microsoft/skills
.NET SDK를 사용하여 Azure Event Grid로 이벤트를 발행하고 수신하세요. EventGridEvent 및 CloudEvent 스키마, 푸시 및 풀 전달 방식, Azure Functions 연동을 지원합니다.
...모든 것을 확장하십시오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://..eventgrid.azure.net/api/events # 필수: Event Grid 토픽 또는 도메인 엔드포인트
EVENT_GRID_TOPIC_KEY= # AzureKeyCredential 인증 시에만 필수
EVENT_GRID_NAMESPACE_ENDPOINT=https://..eventgrid.azure.net # 선택 사항: Event Grid 네임스페이스 엔드포인트
EVENT_GRID_TOPIC_NAME= # 필수: Event Grid 토픽 이름
EVENT_GRID_SUBSCRIPTION_NAME= # 선택 사항: Event Grid 구독 이름
AZURE_TOKEN_CREDENTIALS=prod # 프로덕션 환경에서 DefaultAzureCredential을 사용하는 경우에만 필수
클라이언트 계층 구조
푸시 전달 (토픽/도메인)
└── EventGridPublisherClient
├── SendEventAsync(EventGridEvent)
├── SendEventsAsync(IEnumerable)
├── SendEventAsync(CloudEvent)
└── SendEventsAsync(IEnumerable)
풀 전달 (네임스페이스)
├── 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(""));
Microsoft Entra 토큰 자격 증명
using Azure.Identity;
using Azure.Messaging.EventGrid;
// 로컬 개발: DefaultAzureCredential. 프로덕션: AZURE_TOKEN_CREDENTIALS=prod 또는 AZURE_TOKEN_CREDENTIALS=설정
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 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);
// CloudEvent 일괄 전송
List 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 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);
풀(Pull) 전달 (네임스페이스)
네임스페이스 토픽으로 이벤트 전송
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 lockTokensToAck = new();
List 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($"Subject: {eventGridEvent.Subject}");
log.LogInformation($"Data: {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 웹훅 페이로드
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();
}
}
CloudEvent 구문 분석
CloudEvent[] cloudEvents = CloudEvent.ParseMany(BinaryData.FromString(json));
foreach (CloudEvent cloudEvent in cloudEvents)
{
var data = cloudEvent.Data.ToObjectFromJson();
Console.WriteLine($"유형: {cloudEvent.Type}, 데이터: {data}");
}
시스템 이벤트
// 일반적인 시스템 이벤트 유형
using Azure.Messaging.EventGrid.SystemEvents;
// 스토리지 이벤트
StorageBlobCreatedEventData blobCreated;
StorageBlobDeletedEventData blobDeleted;
// 리소스 이벤트
ResourceWriteSuccessEventData resourceCreated;
ResourceDeleteSuccessEventData resourceDeleted;
// 앱 서비스 이벤트
WebAppUpdatedEventData webAppUpdated;
// 컨테이너 레지스트리 이벤트
ContainerRegistryImagePushedEventData imagePushed;
// IoT 허브 이벤트
IotHubDeviceCreatedEventData deviceCreated;
키 유형 참조
| 유형 | 용도 |
|---|---|
EventGridPublisherClient |
토픽/도메인에 게시 |
EventGridSenderClient |
네임스페이스 토픽으로 전송 |
EventGridReceiverClient |
네임스페이스 구독에서 수신 |
EventGridEvent |
Event Grid 네이티브 스키마 |
CloudEvent |
CloudEvents 1.0 스키마 |
수신 결과 |
풀 전달 응답 |
수신 세부 정보 |
브로커 속성이 포함된 이벤트 |
BrokerProperties |
잠금 토큰, 전달 횟수 |
이벤트 스키마 비교
| 기능 | EventGridEvent | CloudEvent |
|---|---|---|
| 표준 | Azure 전용 | CNCF 표준 |
| 필수 필드 | subject, eventType, dataVersion, data | source, type |
| 확장성 | 제한적 | 확장 속성 |
| 상호 운용성 | Azure 전용 | 크로스 플랫폼 |
모범 사례
- CloudEvents 사용 — 새로운 구현 시 CloudEvents를 우선적으로 사용하십시오(업계 표준)
- 이벤트 일괄 처리 — 효율성을 위해 한 번의 호출로 여러 이벤트를 전송하십시오
- Entra ID 사용 — 액세스 키보다 관리형 ID를 우선적으로 사용하십시오
- 이멱포텐트 핸들러 — 이벤트가 두 번 이상 전달될 수 있음
- 이벤트 TTL 설정 — 네임스페이스 이벤트의 유효 기간(TTL)을 구성하십시오
- 부분적 오류 처리 — 이벤트를 개별적으로 수신 확인하거나 해제하십시오
- 데드레터 사용 — 실패한 이벤트에 대해 데드레터를 구성하십시오
- 스키마 유효성 검사 — 처리 전에 이벤트 데이터의 유효성을 검사하십시오
오류 처리
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.EventGrid |
Azure 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 |
---
name: azure-eventgrid-dotnet
description: Publish and consume events with Azure Event Grid using the .NET SDK. Supports EventGridEvent, CloudEvent schemas, push and pull delivery, and Azure Functions integration.
license: MIT
---
# Azure.Messaging.EventGrid (.NET)
Client library for publishing events to Azure Event Grid topics, domains, and namespaces.
## Installation
```bash
# For topics and domains (push delivery)
dotnet add package Azure.Messaging.EventGrid
# For namespaces (pull delivery)
dotnet add package Azure.Messaging.EventGrid.Namespaces
# For CloudNative CloudEvents interop
dotnet add package Microsoft.Azure.Messaging.EventGrid.CloudNativeCloudEvents
```
**Current Version**: 4.28.0 (stable)
## Environment Variables
```bash
EVENT_GRID_TOPIC_ENDPOINT=https://<topic-name>.<region>.eventgrid.azure.net/api/events # Required: Event Grid topic or domain endpoint
EVENT_GRID_TOPIC_KEY=<access-key> # Only required for AzureKeyCredential auth
EVENT_GRID_NAMESPACE_ENDPOINT=https://<namespace>.<region>.eventgrid.azure.net # Optional: Event Grid namespace endpoint
EVENT_GRID_TOPIC_NAME=<topic-name> # Required: Event Grid topic name
EVENT_GRID_SUBSCRIPTION_NAME=<subscription-name> # Optional: Event Grid subscription name
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```
## Client Hierarchy
```
Push Delivery (Topics/Domains)
└── EventGridPublisherClient
├── SendEventAsync(EventGridEvent)
├── SendEventsAsync(IEnumerable<EventGridEvent>)
├── SendEventAsync(CloudEvent)
└── SendEventsAsync(IEnumerable<CloudEvent>)
Pull Delivery (Namespaces)
├── EventGridSenderClient
│ └── SendAsync(CloudEvent)
└── EventGridReceiverClient
├── ReceiveAsync()
├── AcknowledgeAsync()
├── ReleaseAsync()
└── RejectAsync()
```
## Authentication
### API Key Authentication
```csharp
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 Token Credential
```csharp
using Azure.Identity;
using Azure.Messaging.EventGrid;
// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
var credential = new DefaultAzureCredential(
DefaultAzureCredential.DefaultEnvironmentVariableName
);
// Or use a specific credential directly in production:
// See 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 Token Authentication
```csharp
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);
```
## Publishing Events
### EventGridEvent Schema
```csharp
EventGridPublisherClient client = new(
new Uri(topicEndpoint),
new AzureKeyCredential(topicKey));
// Single event
EventGridEvent egEvent = new(
subject: "orders/12345",
eventType: "Order.Created",
dataVersion: "1.0",
data: new { OrderId = "12345", Amount = 99.99 });
await client.SendEventAsync(egEvent);
// Batch of events
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 Schema
```csharp
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);
// Batch of 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);
```
### Publishing to Event Grid Domain
```csharp
// Events must specify the Topic property for domain routing
List<EventGridEvent> events = new()
{
new EventGridEvent(
subject: "orders/12345",
eventType: "Order.Created",
dataVersion: "1.0",
data: new { OrderId = "12345" })
{
Topic = "orders-topic" // Domain topic name
},
new EventGridEvent(
subject: "inventory/item-1",
eventType: "Inventory.Updated",
dataVersion: "1.0",
data: new { ItemId = "item-1" })
{
Topic = "inventory-topic"
}
};
await client.SendEventsAsync(events);
```
### Custom Serialization
```csharp
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);
```
## Pull Delivery (Namespaces)
### Send Events to Namespace Topic
```csharp
using Azure;
using Azure.Messaging;
using Azure.Messaging.EventGrid.Namespaces;
var senderClient = new EventGridSenderClient(
new Uri(namespaceEndpoint),
topicName,
new AzureKeyCredential(topicKey));
// Send single event
CloudEvent cloudEvent = new("employee_source", "Employee.Created",
new { Name = "John", Age = 30 });
await senderClient.SendAsync(cloudEvent);
// Send batch
await senderClient.SendAsync(new[]
{
new CloudEvent("source", "type", new { Name = "Alice" }),
new CloudEvent("source", "type", new { Name = "Bob" })
});
```
### Receive and Process Events
```csharp
var receiverClient = new EventGridReceiverClient(
new Uri(namespaceEndpoint),
topicName,
subscriptionName,
new AzureKeyCredential(topicKey));
// Receive events
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
{
// Process the event
Console.WriteLine($"Event: {cloudEvent.Type}, Data: {cloudEvent.Data}");
lockTokensToAck.Add(lockToken);
}
catch (Exception)
{
// Release for retry
lockTokensToRelease.Add(lockToken);
}
}
// Acknowledge successfully processed events
if (lockTokensToAck.Any())
{
await receiverClient.AcknowledgeAsync(lockTokensToAck);
}
// Release events for retry
if (lockTokensToRelease.Any())
{
await receiverClient.ReleaseAsync(lockTokensToRelease);
}
```
### Reject Events (Dead Letter)
```csharp
// Reject events that cannot be processed
await receiverClient.RejectAsync(new[] { lockToken });
```
## Consuming Events (Azure Functions)
### EventGridEvent Trigger
```csharp
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($"Event Type: {eventGridEvent.EventType}");
log.LogInformation($"Subject: {eventGridEvent.Subject}");
log.LogInformation($"Data: {eventGridEvent.Data}");
}
}
```
### CloudEvent Trigger
```csharp
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($"Event Type: {cloudEvent.Type}");
logger.LogInformation($"Source: {cloudEvent.Source}");
logger.LogInformation($"Data: {cloudEvent.Data}");
}
}
```
## Parsing Events
### Parse EventGridEvent
```csharp
// From JSON string
string json = "..."; // Event Grid webhook payload
EventGridEvent[] events = EventGridEvent.ParseMany(BinaryData.FromString(json));
foreach (EventGridEvent egEvent in events)
{
if (egEvent.TryGetSystemEventData(out object systemEvent))
{
// Handle system event
switch (systemEvent)
{
case StorageBlobCreatedEventData blobCreated:
Console.WriteLine($"Blob created: {blobCreated.Url}");
break;
}
}
else
{
// Handle custom event
var customData = egEvent.Data.ToObjectFromJson<MyCustomData>();
}
}
```
### Parse CloudEvent
```csharp
CloudEvent[] cloudEvents = CloudEvent.ParseMany(BinaryData.FromString(json));
foreach (CloudEvent cloudEvent in cloudEvents)
{
var data = cloudEvent.Data.ToObjectFromJson<MyEventData>();
Console.WriteLine($"Type: {cloudEvent.Type}, Data: {data}");
}
```
## System Events
```csharp
// Common system event types
using Azure.Messaging.EventGrid.SystemEvents;
// Storage events
StorageBlobCreatedEventData blobCreated;
StorageBlobDeletedEventData blobDeleted;
// Resource events
ResourceWriteSuccessEventData resourceCreated;
ResourceDeleteSuccessEventData resourceDeleted;
// App Service events
WebAppUpdatedEventData webAppUpdated;
// Container Registry events
ContainerRegistryImagePushedEventData imagePushed;
// IoT Hub events
IotHubDeviceCreatedEventData deviceCreated;
```
## Key Types Reference
| Type | Purpose |
|------|---------|
| `EventGridPublisherClient` | Publish to topics/domains |
| `EventGridSenderClient` | Send to namespace topics |
| `EventGridReceiverClient` | Receive from namespace subscriptions |
| `EventGridEvent` | Event Grid native schema |
| `CloudEvent` | CloudEvents 1.0 schema |
| `ReceiveResult` | Pull delivery response |
| `ReceiveDetails` | Event with broker properties |
| `BrokerProperties` | Lock token, delivery count |
## Event Schemas Comparison
| Feature | EventGridEvent | CloudEvent |
|---------|----------------|------------|
| Standard | Azure-specific | CNCF standard |
| Required fields | subject, eventType, dataVersion, data | source, type |
| Extensibility | Limited | Extension attributes |
| Interoperability | Azure only | Cross-platform |
## Best Practices
1. **Use CloudEvents** — Prefer CloudEvents for new implementations (industry standard)
2. **Batch events** — Send multiple events in one call for efficiency
3. **Use Entra ID** — Prefer managed identity over access keys
4. **Idempotent handlers** — Events may be delivered more than once
5. **Set event TTL** — Configure time-to-live for namespace events
6. **Handle partial failures** — Acknowledge/release events individually
7. **Use dead-letter** — Configure dead-letter for failed events
8. **Validate schemas** — Validate event data before processing
## Error Handling
```csharp
using Azure;
try
{
await client.SendEventAsync(cloudEvent);
}
catch (RequestFailedException ex) when (ex.Status == 401)
{
Console.WriteLine("Authentication failed - check credentials");
}
catch (RequestFailedException ex) when (ex.Status == 403)
{
Console.WriteLine("Authorization failed - check RBAC permissions");
}
catch (RequestFailedException ex) when (ex.Status == 413)
{
Console.WriteLine("Payload too large - max 1MB per event, 1MB total batch");
}
catch (RequestFailedException ex)
{
Console.WriteLine($"Event Grid error: {ex.Status} - {ex.Message}");
}
```
## Failover Pattern
```csharp
try
{
var primaryClient = new EventGridPublisherClient(primaryUri, primaryKey);
await primaryClient.SendEventsAsync(events);
}
catch (RequestFailedException)
{
// Failover to secondary region
var secondaryClient = new EventGridPublisherClient(secondaryUri, secondaryKey);
await secondaryClient.SendEventsAsync(events);
}
```
## Related SDKs
| SDK | Purpose | Install |
|-----|---------|---------|
| `Azure.Messaging.EventGrid` | Topics/Domains (this SDK) | `dotnet add package Azure.Messaging.EventGrid` |
| `Azure.Messaging.EventGrid.Namespaces` | Pull delivery | `dotnet add package Azure.Messaging.EventGrid.Namespaces` |
| `Azure.Identity` | Authentication | `dotnet add package Azure.Identity` |
| `Microsoft.Azure.WebJobs.Extensions.EventGrid` | Azure Functions trigger | `dotnet add package Microsoft.Azure.WebJobs.Extensions.EventGrid` |
## Reference Links
| Resource | URL |
|----------|-----|
| NuGet Package | https://www.nuget.org/packages/Azure.Messaging.EventGrid |
| API Reference | https://learn.microsoft.com/dotnet/api/azure.messaging.eventgrid |
| Quickstart | https://learn.microsoft.com/azure/event-grid/custom-event-quickstart |
| Pull Delivery | https://learn.microsoft.com/azure/event-grid/pull-delivery-overview |
| GitHub Source | https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/eventgrid/Azure.Messaging.EventGrid |
모든 파일
0개 파일azure-eventgrid-dotnet 설치
스킬 파일을 다운로드하여 .claude/skills/ 디렉터리에 압축을 풀어주세요.
ZIP 다운로드저장소를 클론하고 스킬 파일을 프로젝트에 복사하세요.
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-dotnet/skills/azure-eventgrid-dotnet # Copy SKILL.md to your .claude/skills/ directory
복사





집
