Azure.Messaging.EventGrid 4.24.0

The ID prefix of this package has been reserved for one of the owners of this package by Prefix Reserved
dotnet add package Azure.Messaging.EventGrid --version 4.24.0
NuGet\Install-Package Azure.Messaging.EventGrid -Version 4.24.0
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Azure.Messaging.EventGrid" Version="4.24.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Azure.Messaging.EventGrid --version 4.24.0
#r "nuget: Azure.Messaging.EventGrid, 4.24.0"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Azure.Messaging.EventGrid as a Cake Addin
#addin nuget:?package=Azure.Messaging.EventGrid&version=4.24.0

// Install Azure.Messaging.EventGrid as a Cake Tool
#tool nuget:?package=Azure.Messaging.EventGrid&version=4.24.0

Azure Event Grid client library for .NET

Azure Event Grid allows you to easily build applications with event-based architectures. The Event Grid service fully manages all routing of events from any source, to any destination, for any application. Azure service events and custom events can be published directly to the service, where the events can then be filtered and sent to various recipients, such as built-in handlers or custom webhooks. To learn more about Azure Event Grid: What is Event Grid?

Use the client library for Azure Event Grid to:

Getting started

Install the package

Install the client library from NuGet:

dotnet add package Azure.Messaging.EventGrid


You must have an Azure subscription and an Azure resource group with a custom Event Grid topic or domain. Follow this step-by-step tutorial to register the Event Grid resource provider and create Event Grid topics using the Azure portal. There is a similar tutorial using Azure CLI.

Authenticate the Client

In order for the client library to interact with a topic or domain, you will need the endpoint of the Event Grid topic and a credential, which can be created using the topic's access key.

You can find the endpoint for your Event Grid topic either in the Azure Portal or by using the Azure CLI snippet below.

az eventgrid topic show --name <your-resource-name> --resource-group <your-resource-group-name> --query "endpoint"

The access key can also be found through the portal, or by using the Azure CLI snippet below:

az eventgrid topic key list --name <your-resource-name> --resource-group <your-resource-group-name> --query "key1"
Authenticate using Topic Access Key

Once you have your access key and topic endpoint, you can create the publisher client as follows:

EventGridPublisherClient client = new EventGridPublisherClient(
    new Uri("<endpoint>"),
    new AzureKeyCredential("<access-key>"));
Authenticate using Shared Access Signature

Event Grid also supports authenticating with a shared access signature which allows for providing access to a resource that expires by a certain time without sharing your access key. Generally, the workflow would be that one application would generate the SAS string and hand off the string to another application that would consume the string. Generate the SAS:

var builder = new EventGridSasBuilder(new Uri(topicEndpoint), DateTimeOffset.Now.AddHours(1));
var keyCredential = new AzureKeyCredential(topicAccessKey);
string sasToken = builder.GenerateSas(keyCredential);

Here is how it would be used from the consumer's perspective:

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

EventGridPublisherClient also accepts a set of configuring options through EventGridPublisherClientOptions. For example, you can specify a custom serializer that will be used to serialize the event data to JSON.

Authenticate using Microsoft Entra ID

Azure Event Grid provides integration with Microsoft Entra ID for identity-based authentication of requests. With Azure AD, you can use role-based access control (RBAC) to grant access to your Azure Event Grid resources to users, groups, or applications. The Azure Identity library provides easy Microsoft Entra ID support for authentication.

To send events to a topic or domain using Microsoft Entra ID, the authenticated identity should have the "EventGrid Data Sender" role assigned.

EventGridPublisherClient client = new EventGridPublisherClient(
    new Uri(topicEndpoint),
    new DefaultAzureCredential());

Key concepts

For information about general Event Grid concepts: Concepts in Azure Event Grid.


A publisher sends events to the Event Grid service. Microsoft publishes events for several Azure services. You can publish events from your own application using the EventGridPublisherClient.

Event schemas

An event is the smallest amount of information that fully describes something that happened in the system. Event Grid supports multiple schemas for encoding events. When a custom topic or domain is created, you specify the schema that will be used when publishing events.

Event Grid schema

While you may configure your topic to use a custom schema, it is more common to use the already-defined Event Grid schema. See the specifications and requirements here.

CloudEvents v1.0 schema

Another option is to use the CloudEvents v1.0 schema. CloudEvents is a Cloud Native Computing Foundation project which produces a specification for describing event data in a common way. The service summary of CloudEvents can be found here.

Regardless of what schema your topic or domain is configured to use, EventGridPublisherClient will be used to publish events to it. Use the SendEvents or SendEventsAsync method for publishing.

Event delivery

Events delivered to consumers by Event Grid are delivered as JSON. Depending on the type of consumer being delivered to, the Event Grid service may deliver one or more events as part of a single payload. Handling events will be different based on which schema the event was delivered as. However, the general pattern will remain the same:

  • Parse events from JSON into individual events. Based on the event schema (Event Grid or CloudEvents), you can now access basic information about the event on the envelope (properties that are present for all events, like event time and type).
  • Deserialize the event data. Given an EventGridEvent or CloudEvent, the user can attempt to access the event payload, or data, by deserializing to a specific type. You can supply a custom serializer at this point to correctly decode the data.

Thread safety

We guarantee that all client instance methods are thread-safe and independent of each other (guideline). This ensures that the recommendation of reusing client instances is always safe, even across threads.

Additional concepts

Client options | Accessing the response | Long-running operations | Handling failures | Diagnostics | Mocking | Client lifetime


Publish Event Grid events to an Event Grid Topic

Publishing events to Event Grid is performed using the EventGridPublisherClient. Use the provided SendEvent/SendEventAsync method to publish a single event to the topic.

// Add EventGridEvents to a list to publish to the topic
EventGridEvent egEvent =
    new EventGridEvent(
        "This is the event data");

// Send the event
await client.SendEventAsync(egEvent);

To publish a batch of events, use the SendEvents/SendEventsAsync method.

// Example of a custom ObjectSerializer used to serialize the event payload to JSON
var myCustomDataSerializer = new JsonObjectSerializer(
    new JsonSerializerOptions()
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase

// Add EventGridEvents to a list to publish to the topic
List<EventGridEvent> eventsList = new List<EventGridEvent>
    // EventGridEvent with custom model serialized to JSON
    new EventGridEvent(
        new CustomModel() { A = 5, B = true }),

    // EventGridEvent with custom model serialized to JSON using a custom serializer
    new EventGridEvent(
        myCustomDataSerializer.Serialize(new CustomModel() { A = 5, B = true })),

// Send the events
await client.SendEventsAsync(eventsList);

Publish CloudEvents to an Event Grid Topic

Publishing events to Event Grid is performed using the EventGridPublisherClient. Use the provided SendEvents/SendEventsAsync method to publish events to the topic.

// Example of a custom ObjectSerializer used to serialize the event payload to JSON
var myCustomDataSerializer = new JsonObjectSerializer(
    new JsonSerializerOptions()
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase

// Add CloudEvents to a list to publish to the topic
List<CloudEvent> eventsList = new List<CloudEvent>
    // CloudEvent with custom model serialized to JSON
    new CloudEvent(
        new CustomModel() { A = 5, B = true }),

    // CloudEvent with custom model serialized to JSON using a custom serializer
    new CloudEvent(
        myCustomDataSerializer.Serialize(new CustomModel() { A = 5, B = true }),

    // CloudEvents also supports sending binary-valued data
    new CloudEvent(
        new BinaryData(Encoding.UTF8.GetBytes("This is treated as binary data")),

// Send the events
await client.SendEventsAsync(eventsList);

Publish Event Grid events to an Event Grid Domain

An event domain is a management tool for large numbers of Event Grid topics related to the same application. You can think of it as a meta-topic that can have thousands of individual topics. When you create an event domain, you're given a publishing endpoint similar to if you had created a topic in Event Grid.

To publish events to any topic in an Event Domain, push the events to the domain's endpoint the same way you would for a custom topic. The only difference is that you must specify the topic you'd like the event to be delivered to.

// Add EventGridEvents to a list to publish to the domain
// Don't forget to specify the topic you want the event to be delivered to!
List<EventGridEvent> eventsList = new List<EventGridEvent>
    new EventGridEvent(
        "This is the event data")
        Topic = "MyTopic"

// Send the events
await client.SendEventsAsync(eventsList);

For sending CloudEvents, the CloudEvent source is used as the domain topic:

List<CloudEvent> eventsList = new List<CloudEvent>();

for (int i = 0; i < 10; i++)
    CloudEvent cloudEvent = new CloudEvent(
        // the source is mapped to the domain topic
        Id = $"event-{i}",
        Time = DateTimeOffset.Now

await client.SendEventsAsync(eventsList);

Receiving and Deserializing Events

There are several different Azure services that act as event handlers.

Note: if using Webhooks for event delivery of the Event Grid schema, Event Grid requires you to prove ownership of your Webhook endpoint before it starts delivering events to that endpoint. At the time of event subscription creation, Event Grid sends a subscription validation event to your endpoint, as seen below. Learn more about completing the handshake here: Webhook event delivery. For the CloudEvents schema, the service validates the connection using the HTTP options method. Learn more here: CloudEvents validation.

Once events are delivered to the event handler, we can deserialize the JSON payload into a list of events.

Using EventGridEvent:

// Parse the JSON payload into a list of events
EventGridEvent[] egEvents = EventGridEvent.ParseMany(BinaryData.FromStream(httpContent));

Using CloudEvent:

var bytes = await httpContent.ReadAsByteArrayAsync();
// Parse the JSON payload into a list of events
CloudEvent[] cloudEvents = CloudEvent.ParseMany(new BinaryData(bytes));
Deserializing event data

From here, one can access the event data by deserializing to a specific type by calling ToObjectFromJson<T>() on the Data property. In order to deserialize to the correct type, the EventType property (Type for CloudEvents) helps distinguish between different events. Custom event data should be deserialized using the generic method ToObjectFromJson<T>(). There is also an extension method ToObject<T>() that accepts a custom ObjectSerializer to deserialize the event data.

foreach (CloudEvent cloudEvent in cloudEvents)
    switch (cloudEvent.Type)
        case "Contoso.Items.ItemReceived":
            // By default, ToObjectFromJson<T> uses System.Text.Json to deserialize the payload
            ContosoItemReceivedEventData itemReceived = cloudEvent.Data.ToObjectFromJson<ContosoItemReceivedEventData>();
        case "MyApp.Models.CustomEventType":
            // One can also specify a custom ObjectSerializer as needed to deserialize the payload correctly
            TestPayload testPayload = cloudEvent.Data.ToObject<TestPayload>(myCustomSerializer);
        case SystemEventNames.StorageBlobDeleted:
            // Example for deserializing system events using ToObjectFromJson<T>
            StorageBlobDeletedEventData blobDeleted = cloudEvent.Data.ToObjectFromJson<StorageBlobDeletedEventData>();

Using TryGetSystemEventData():

If expecting mostly system events, it may be cleaner to switch on TryGetSystemEventData() and use pattern matching to act on the individual events. If an event is not a system event, the method will return false and the out parameter will be null.

As a caveat, if you are using a custom event type with an EventType value that later gets added as a system event by the service and SDK, the return value of TryGetSystemEventData would change from false to true. This could come up if you are pre-emptively creating your own custom events for events that are already being sent by the service, but have not yet been added to the SDK. In this case, it is better to use the generic ToObjectFromJson<T> method on the Data property so that your code flow doesn't change automatically after upgrading (of course, you may still want to modify your code to consume the newly released system event model as opposed to your custom model).

foreach (EventGridEvent egEvent in egEvents)
    // If the event is a system event, TryGetSystemEventData will return the deserialized system event
    if (egEvent.TryGetSystemEventData(out object systemEvent))
        switch (systemEvent)
            case SubscriptionValidationEventData subscriptionValidated:
            case StorageBlobCreatedEventData blobCreated:
            // Handle any other system event type
                // we can get the raw Json for the event using Data
        switch (egEvent.EventType)
            case "MyApp.Models.CustomEventType":
                TestPayload deserializedEventData = egEvent.Data.ToObjectFromJson<TestPayload>();
            // Handle any other custom event type


Service Responses

SendEvents() returns an HTTP response code from the service. A RequestFailedException is thrown as a service response for any unsuccessful requests. The exception contains information about what response code was returned from the service.

Deserializing Event Data

  • If the event data is not valid JSON, a JsonException will be thrown when calling Parse or ParseMany.
  • If the event schema does not correspond to the type being deserialized to (e.g. calling CloudEvent.Parse on an EventGridSchema event), an ArgumentException is thrown.
  • If Parse is called on data that contains multiple events, an ArgumentException is thrown. ParseMany should be used here instead.

Setting up console logging

You can also easily enable console logging if you want to dig deeper into the requests you're making against the service.

Distributed Tracing

The Event Grid library supports distributing tracing out of the box. In order to adhere to the CloudEvents specification's guidance on distributing tracing, the library will set the traceparent and tracestate on the ExtensionAttributes of a CloudEvent when distributed tracing is enabled. To learn more about how to enable distributed tracing in your application, take a look at the Azure SDK distributed tracing documentation.

Event Grid on Kubernetes

This library has been tested and validated on Kubernetes using Azure Arc.

Next steps

View more here for common usages of the Event Grid client library: Event Grid Samples.


This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit Contributor License Agreements.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact with any additional questions or comments.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (37)

Showing the top 5 NuGet packages that depend on Azure.Messaging.EventGrid:

Package Downloads
Microsoft.Extensions.Configuration.AzureAppConfiguration The ID prefix of this package has been reserved for one of the owners of this package by

Microsoft.Extensions.Configuration.AzureAppConfiguration is a configuration provider for the .NET Core framework that allows developers to use Microsoft Azure App Configuration service as a configuration source in their applications.

Microsoft.Azure.WebJobs.Extensions.EventGrid The ID prefix of this package has been reserved for one of the owners of this package by

This extension adds bindings for EventGrid

Microsoft.Azure.Functions.Worker.Extensions.EventGrid The ID prefix of this package has been reserved for one of the owners of this package by

Azure Event Grid extensions for .NET isolated functions


Package Description

Microsoft.Azure.Messaging.EventGrid.CloudNativeCloudEvents The ID prefix of this package has been reserved for one of the owners of this package by

This library allows the CloudEvent model from CloudNative.CloudEvents to be published using the Azure Event Grid client library.

GitHub repositories (7)

Showing the top 5 popular GitHub repositories that depend on Azure.Messaging.EventGrid:

Repository Stars
The core infrastructure backend (API, database, Docker, etc).
A self-hosted Fuzzing-As-A-Service platform
AZ-204: Developing solutions for Microsoft Azure
Full-stack .Net 8 Clean Architecture (Microservices, Modular Monolith, Monolith), Blazor, Angular 17, React 18, Vue 3, BFF with YARP, Domain-Driven Design, CQRS, SOLID, Asp.Net Core Identity Custom Storage, OpenID Connect, Entity Framework Core, Selenium, SignalR, Hosted Services, Health Checks, Rate Limiting, Cloud Services (Azure, AWS, Google)...
Virto Commerce B2B Innovation Platform
Version Downloads Last updated
4.24.0 159,769 4/9/2024
4.23.0 145,990 3/11/2024
4.22.0 157,218 2/13/2024
4.22.0-beta.1 33,829 11/13/2023
4.21.0 995,298 11/9/2023
4.20.0 186,998 10/18/2023
4.19.0 34,921 10/13/2023
4.18.0 189,818 9/13/2023
4.18.0-beta.1 2,007 7/16/2023
4.17.0 912,384 6/9/2023
4.17.0-beta.2 225 6/7/2023
4.17.0-beta.1 765 5/22/2023
4.16.0 221,764 5/11/2023
4.15.0 254,291 4/17/2023
4.14.1 759,388 3/13/2023
4.14.0 64,157 3/8/2023
4.13.0 430,482 1/20/2023
4.12.0 671,756 11/8/2022
4.11.0 1,570,709 7/12/2022
4.11.0-beta.2 2,573 5/10/2022
4.11.0-beta.1 1,424 4/8/2022
4.10.0 2,521,052 4/7/2022
4.9.0 361,969 3/9/2022
4.8.2 197,621 2/9/2022
4.8.1 822,565 1/12/2022
4.7.0 31,477,114 10/7/2021
4.6.0 539,837 8/13/2021
4.5.0 238,174 7/19/2021
4.4.0 171,486 6/21/2021
4.3.0 296,938 6/8/2021
4.2.0 119,551 5/11/2021
4.1.0 182,941 3/23/2021
4.0.0 59,051 3/15/2021
4.0.0-beta.5 14,812 2/9/2021
4.0.0-beta.4 82,528 11/10/2020
4.0.0-beta.3 4,142 10/7/2020
4.0.0-beta.2 43,265 9/24/2020
4.0.0-beta.1 996 9/8/2020