azure-eventgrid-dotnet
microsoft/skills
Publiez et consultez des événements avec Azure Event Grid à l'aide du SDK .NET. Prend en charge les schémas EventGridEvent et CloudEvent, la diffusion de type « push » et « pull », ainsi que l'intégration à Azure Functions.
...Développer toutAzure.Messaging.EventGrid (.NET)
Bibliothèque cliente permettant de publier des événements vers des sujets, des domaines et des espaces de noms Azure Event Grid.
Installation
# Pour les sujets et les domaines (diffusion push)
dotnet add package Azure.Messaging.EventGrid
# Pour les espaces de noms (diffusion de type « pull »)
dotnet add package Azure.Messaging.EventGrid.Namespaces
# Pour l'interopérabilité CloudNative CloudEvents
dotnet add package Microsoft.Azure.Messaging.EventGrid.CloudNativeCloudEvents
Version actuelle: 4.28.0 (stable)
Variables d’environnement
EVENT_GRID_TOPIC_ENDPOINT=https://..eventgrid.azure.net/api/events # Obligatoire : point de terminaison du sujet ou du domaine Event Grid
EVENT_GRID_TOPIC_KEY= # Obligatoire uniquement pour l'authentification AzureKeyCredential
EVENT_GRID_NAMESPACE_ENDPOINT=https://..eventgrid.azure.net # Facultatif : point de terminaison de l'espace de noms Event Grid
EVENT_GRID_TOPIC_NAME= # Obligatoire : nom du sujet Event Grid
EVENT_GRID_SUBSCRIPTION_NAME= # Facultatif : nom de l’abonnement Event Grid
AZURE_TOKEN_CREDENTIALS=prod # Requis uniquement si DefaultAzureCredential est utilisé en production
Hiérarchie du client
Diffusion par push (sujets/domaines)
└── EventGridPublisherClient
├── SendEventAsync(EventGridEvent)
├── SendEventsAsync(IEnumerable)
├── SendEventAsync(CloudEvent)
└── SendEventsAsync(IEnumerable)
Diffusion de type « pull » (espaces de noms)
├── EventGridSenderClient
│ └── SendAsync(CloudEvent)
└── EventGridReceiverClient
├── ReceiveAsync()
├── AcknowledgeAsync()
├── ReleaseAsync()
└── RejectAsync()
Authentification
Authentification par clé API
using Azure;
using Azure.Messaging.EventGrid;
EventGridPublisherClient client = new(
new Uri("https://mytopic.eastus-1.eventgrid.azure.net/api/events"),
new AzureKeyCredential(""));
Identifiants de jeton Microsoft Entra
using Azure.Identity;
using Azure.Messaging.EventGrid;
// Développement local : DefaultAzureCredential. En production : définissez AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=
var credential = new DefaultAzureCredential(
DefaultAzureCredential.DefaultEnvironmentVariableName
);
// Ou utilisez directement des informations d’identification spécifiques en production :
// Voir 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);
Authentification par jeton 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);
Publication d’événements
Schéma EventGridEvent
EventGridPublisherClient client = new(
new Uri(topicEndpoint),
new AzureKeyCredential(topicKey));
// Événement unique
EventGridEvent egEvent = new(
subject: "orders/12345",
eventType : « Order.Created »,
dataVersion : « 1.0 »,
data : new { OrderId = « 12345 », Amount = 99,99 });
await client.SendEventAsync(egEvent);
// Lot d’événements
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);
Schéma 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);
// Lot de CloudEvents
List cloudEvents = new()
{
new CloudEvent("/orders", "Order.Created", new { OrderId = "1" }),
new CloudEvent("/orders", "Order.Updated", new { OrderId = "2" })
};
await client.SendEventsAsync(cloudEvents);
Publication vers un domaine Event Grid
// Les événements doivent spécifier la propriété Topic pour le routage vers le domaine
List events = new()
{
new EventGridEvent(
subject: "orders/12345",
eventType: "Order.Created",
dataVersion: "1.0",
data: new { OrderId = "12345" })
{
Topic = "orders-topic" // Nom du sujet du domaine
},
new EventGridEvent(
subject: "inventory/item-1",
eventType: "Inventory.Updated",
dataVersion: "1.0",
data: new { ItemId = "item-1" })
{
Topic = "inventory-topic"
}
};
await client.SendEventsAsync(events);
Sérialisation personnalisée
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);
Diffusion par extraction (espaces de noms)
Envoyer des événements vers un sujet d’espace de noms
using Azure;
using Azure.Messaging;
using Azure.Messaging.EventGrid.Namespaces;
var senderClient = new EventGridSenderClient(
new Uri(namespaceEndpoint),
topicName,
new AzureKeyCredential(topicKey));
// Envoyer un événement unique
CloudEvent cloudEvent = new("employee_source", "Employee.Created",
new { Name = "John", Age = 30 });
await senderClient.SendAsync(cloudEvent);
// Envoyer un lot
await senderClient.SendAsync(new[]
{
new CloudEvent("source", "type", new { Name = "Alice" }),
new CloudEvent("source", "type", new { Name = "Bob" })
});
Réception et traitement des événements
var receiverClient = new EventGridReceiverClient(
new Uri(namespaceEndpoint),
topicName,
subscriptionName,
new AzureKeyCredential(topicKey));
// Réception des événements
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
{
// Traiter l’événement
Console.WriteLine($"Événement : {cloudEvent.Type}, Données : {cloudEvent.Data}");
lockTokensToAck.Add(lockToken);
}
catch (Exception)
{
// Libérer pour une nouvelle tentative
lockTokenToRelease.Add(lockToken);
}
}
// Accuser réception des événements traités avec succès
if (lockTokenToAck.Any())
{
await receiverClient.AcknowledgeAsync(lockTokensToAck);
}
// Libérer les événements pour une nouvelle tentative
if (lockTokensToRelease.Any())
{
await receiverClient.ReleaseAsync(lockTokensToRelease);
}
Rejeter des événements (boîte aux lettres morte)
// Rejeter les événements qui ne peuvent pas être traités
await receiverClient.RejectAsync(new[] { lockToken });
Consommation d’événements (Azure Functions)
Déclencheur 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($"Type d'événement : {eventGridEvent.EventType}");
log.LogInformation($"Objet : {eventGridEvent.Subject}");
log.LogInformation($"Données : {eventGridEvent.Data}");
}
}
Déclencheur 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($"Type d'événement : {cloudEvent.Type}");
logger.LogInformation($"Source : {cloudEvent.Source}");
logger.LogInformation($"Données : {cloudEvent.Data}");
}
}
Analyse des événements
Analyser un EventGridEvent
// À partir d’une chaîne JSON
string json = "..."; // Charge utile du webhook Event Grid
EventGridEvent[] events = EventGridEvent.ParseMany(BinaryData.FromString(json));
foreach (EventGridEvent egEvent in events)
{
if (egEvent.TryGetSystemEventData(out object systemEvent))
{
// Gestion de l’événement système
switch (systemEvent)
{
case StorageBlobCreatedEventData blobCreated:
Console.WriteLine($"Blob créé : {blobCreated.Url}");
break;
}
}
else
{
// Traitement d’un événement personnalisé
var customData = egEvent.Data.ToObjectFromJson();
}
}
Analyser CloudEvent
CloudEvent[] cloudEvents = CloudEvent.ParseMany(BinaryData.FromString(json));
foreach (CloudEvent cloudEvent in cloudEvents)
{
var data = cloudEvent.Data.ToObjectFromJson();
Console.WriteLine($"Type : {cloudEvent.Type}, Données : {data}");
}
Événements système
// Types d’événements système courants
using Azure.Messaging.EventGrid.SystemEvents;
// Événements de stockage
StorageBlobCreatedEventData blobCreated;
StorageBlobDeletedEventData blobDeleted;
// Événements de ressource
ResourceWriteSuccessEventData resourceCreated;
ResourceDeleteSuccessEventData resourceDeleted;
// Événements App Service
WebAppUpdatedEventData webAppUpdated;
// Événements du registre de conteneurs
ContainerRegistryImagePushedEventData imagePushed;
// Événements IoT Hub
IotHubDeviceCreatedEventData deviceCreated;
Référence des types de clés
| Type | Objectif |
|---|---|
EventGridPublisherClient |
Publication vers des sujets/domaines |
EventGridSenderClient |
Envoyer vers des sujets d'espace de noms |
EventGridReceiverClient |
Recevoir depuis les abonnements d'un espace de noms |
EventGridEvent |
Schéma natif d'Event Grid |
CloudEvent |
Schéma CloudEvents 1.0 |
ReceiveResult |
Réponse de livraison par extraction |
ReceiveDetails |
Événement avec propriétés du courtier |
Propriétés du courtier |
Jeton de verrouillage, nombre de livraisons |
Comparaison des schémas d'événements
| Fonctionnalité | EventGridEvent | CloudEvent |
|---|---|---|
| Standard | Spécifique à Azure | Norme CNCF |
| Champs obligatoires | subject, eventType, dataVersion, data | source, type |
| Extensibilité | Limitée | Attributs d'extension |
| Interopérabilité | Azure uniquement | Multiplateforme |
Meilleures pratiques
- Utilisez CloudEvents — Privilégiez CloudEvents pour les nouvelles implémentations (norme industrielle)
- Événements groupés — Envoyez plusieurs événements en un seul appel pour plus d’efficacité
- Utilisez Entra ID — Privilégiez les identités gérées plutôt que les clés d’accès
- Gestionnaires idempotents — Les événements peuvent être transmis plusieurs fois
- Définir la durée de vie (TTL) des événements — Configurez la durée de vie des événements de l'espace de noms
- Gérer les échecs partiels — Accuser réception ou relâcher les événements individuellement
- Utiliser la file d’attente des messages perdus — Configurer la file d’attente des messages perdus pour les événements ayant échoué
- Valider les schémas — Valider les données des événements avant leur traitement
Gestion des erreurs
à l'aide d'Azure ;
try
{
await client.SendEventAsync(cloudEvent);
}
catch (RequestFailedException ex) when (ex.Status == 401)
{
Console.WriteLine("Échec de l'authentification - vérifiez les informations d'identification");
}
catch (RequestFailedException ex) when (ex.Status == 403)
{
Console.WriteLine("Échec de l'autorisation — vérifiez les autorisations RBAC");
}
catch (RequestFailedException ex) when (ex.Status == 413)
{
Console.WriteLine("Charge utile trop volumineuse – 1 Mo maximum par événement, 1 Mo au total par lot");
}
catch (RequestFailedException ex)
{
Console.WriteLine($"Erreur Event Grid : {ex.Status} - {ex.Message}");
}
Modèle de basculement
try
{
var primaryClient = new EventGridPublisherClient(primaryUri, primaryKey);
await primaryClient.SendEventsAsync(events);
}
catch (RequestFailedException)
{
// Basculement vers la région secondaire
var secondaryClient = new EventGridPublisherClient(secondaryUri, secondaryKey);
await secondaryClient.SendEventsAsync(events);
}
SDK associés
| SDK | Objectif | Installation |
|---|---|---|
Azure.Messaging.EventGrid |
Thèmes/Domaines (ce SDK) | dotnet add package Azure.Messaging.EventGrid |
Azure.Messaging.EventGrid.Namespaces |
Distribution par extraction | dotnet add package Azure.Messaging.EventGrid.Namespaces |
Azure.Identity |
Authentification | dotnet add package Azure.Identity |
Microsoft.Azure.WebJobs.Extensions.EventGrid |
Déclencheur Azure Functions | dotnet add package Microsoft.Azure.WebJobs.Extensions.EventGrid |
Liens de référence
| Ressource | URL |
|---|---|
| Package NuGet | https://www.nuget.org/packages/Azure.Messaging.EventGrid |
| Référence API | https://learn.microsoft.com/dotnet/api/azure.messaging.eventgrid |
| Guide de démarrage | https://learn.microsoft.com/azure/event-grid/custom-event-quickstart |
| Livraison par pull | https://learn.microsoft.com/azure/event-grid/pull-delivery-overview |
| Source 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 |
Tous les fichiers
0 fichiersInstaller azure-eventgrid-dotnet
Téléchargez et décompressez les fichiers de compétences dans votre répertoire .claude/skills/.
Télécharger le ZIPClonez le dépôt et copiez les fichiers de compétence dans votre projet.
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
Copier





Maison
