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);
拉取式传输(命名空间)
将事件发送到命名空间主题
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)
EventGrid 事件触发器
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();
}
}
解析 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 架构 |
接收结果 |
拉取式交付响应 |
接收详情 |
包含经纪人属性的事件 |
BrokerProperties |
锁定令牌、投递次数 |
事件模式比较
| 功能 | EventGridEvent | CloudEvent |
|---|---|---|
| 标准 | Azure 专属 | CNCF 标准 |
| 必填字段 | subject、eventType、dataVersion、data | source, type |
| 可扩展性 | 有限 | 扩展属性 |
| 互操作性 | 仅限 Azure | 跨平台 |
最佳实践
- 使用 CloudEvents—— 新实现应优先采用 CloudEvents(行业标准)
- 批量事件— 为提高效率,请在一次调用中发送多个事件
- 使用 Entra ID— 建议优先使用托管身份,而非访问密钥
- 幂等处理程序— 事件可能会被投递多次
- 设置事件 TTL— 为命名空间事件配置生存时间
- 处理部分失败— 逐个确认/释放事件
- 使用死信箱— 为失败的事件配置死信箱
- 验证模式— 在处理前验证事件数据
错误处理
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.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
复制





首页
