azure-eventgrid-dotnet
microsoft/skills
Публикуйте и обрабатывайте события с помощью Azure Event Grid с использованием SDK для .NET. Поддерживаются схемы EventGridEvent и CloudEvent, способы доставки «push» и «pull», а также интеграция с Azure Functions.
...Расширить всеAzure.Messaging.EventGrid (.NET)
Клиентская библиотека для публикации событий в темы, домены и пространства имён Azure Event Grid.
Установка
# Для тем и доменов (доставка по принципу push)
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
Иерархия клиента
Доставка по принципу push (темы/домены)
└── 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);
Доставка по запросу (пространства имён)
Отправка событий в тему пространства имён
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)
{
// Освободить для повторной попытки
lockTokenToRelease.Add(lockToken);
}
}
// Подтвердить успешно обработанные события
if (lockTokenToAck.Any())
{
await receiverClient.AcknowledgeAsync(lockTokensToAck);
}
// Освободить события для повторной попытки
if (lockTokensToRelease.Any())
{
await receiverClient.ReleaseAsync(lockTokensToRelease);
}
Отклонение событий (Dead Letter)
// Отклонение событий, которые не могут быть обработаны
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
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 Hub
IotHubDeviceCreatedEventData deviceCreated;
Справочник типов ключей
| Тип | Назначение |
|---|---|
EventGridPublisherClient |
Публикация в темы/домены |
EventGridSenderClient |
Отправка в темы пространства имен |
EventGridReceiverClient |
Прием из подписок пространства имен |
EventGridEvent |
Нативная схема Event Grid |
CloudEvent |
Схема CloudEvents 1.0 |
ReceiveResult |
Ответ на доставку по методу pull |
ReceiveDetails |
Событие со свойствами брокера |
BrokerProperties |
Токен блокировки, количество доставок |
Сравнение схем событий
| Функция | EventGridEvent | CloudEvent |
|---|---|---|
| Стандарт | Специфично для Azure | Стандарт CNCF |
| Обязательные поля | subject, eventType, dataVersion, data | source, type |
| Расширяемость | Ограниченная | Атрибуты расширения |
| Взаимодействие | Только для Azure | Кроссплатформенность |
Рекомендации
- Используйте CloudEvents — отдавайте предпочтение CloudEvents при новых внедрениях (отраслевой стандарт)
- Пакетная отправка событий — отправляйте несколько событий одним вызовом для повышения эффективности
- Используйте Entra ID — отдавайте предпочтение управляемым идентификаторам вместо ключей доступа
- Идемпотентные обработчики — события могут доставляться более одного раза
- Установите TTL события — настройте время жизни событий пространства имен
- Обработка частичных сбоев — подтверждайте или отбрасывайте события по отдельности
- Используйте механизм «dead-letter» — настройте механизм «dead-letter» для событий, доставка которых завершилась сбоем
- Проверка схем — Проверка данных событий перед обработкой
Обработка ошибок
с использованием 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("Слишком большой объем данных — не более 1 МБ на одно событие, 1 МБ на весь пакет");
}
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
Копировать





Дом
