|

|  How to Integrate Microsoft Azure Event Grid API in .NET

How to Integrate Microsoft Azure Event Grid API in .NET

October 31, 2024

Discover step-by-step guidance to seamlessly integrate Microsoft Azure Event Grid API into your .NET applications for efficient event-driven solutions.

How to Integrate Microsoft Azure Event Grid API in .NET

 

Prerequisites

 

  • You should have a basic understanding of how Azure Event Grid works and be familiar with .NET Core or .NET 5/6.
  •  

  • Ensure you have set up your Azure environment and have access to Azure Portal to manage your Event Grid configurations.

 

Install Necessary NuGet Packages

 

  • Before starting, make sure to install the following NuGet packages in your .NET project:
    • Microsoft.Azure.EventGrid
    • Newtonsoft.Json (often needed for serialization/deserialization of events)

 

dotnet add package Microsoft.Azure.EventGrid
dotnet add package Newtonsoft.Json

 

Configure Event Grid Topic

 

  • Retrieve your Azure Event Grid Topic endpoint and access key from the Azure Portal. You will need these to authenticate your requests.
  •  

  • Ensure your Event Grid topic has been set up to accept the events you're interested in publishing or subscribing to.
  •  

  • Create a configuration section in your appsettings.json for storing Event Grid related configurations:

 

{
  "EventGrid": {
    "TopicEndpoint": "YOUR_EVENT_GRID_TOPIC_ENDPOINT",
    "AccessKey": "YOUR_ACCESS_KEY"
  }
}

 

Publishing Events to Event Grid

 

  • Create a method to publish events to your Event Grid:

 

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Azure.EventGrid;
using Microsoft.Azure.EventGrid.Models;
using Newtonsoft.Json;

public class EventGridPublisher
{
    private static string topicEndpoint = "YOUR_EVENT_GRID_TOPIC_ENDPOINT";
    private static string accessKey = "YOUR_ACCESS_KEY";

    public async Task PublishEventAsync()
    {
        string topicHostname = new Uri(topicEndpoint).Host;
        var topicCredentials = new TopicCredentials(accessKey);
        var client = new EventGridClient(topicCredentials);

        var events = new List<EventGridEvent>
        {
            new EventGridEvent
            {
                Id = Guid.NewGuid().ToString(),
                EventType = "My.CustomEventType",
                Data = new { Message = "Hello, Event Grid!" },
                EventTime = DateTime.Now,
                Subject = "MyEvent",
                DataVersion = "1.0"
            }
        };

        await client.PublishEventsAsync(topicHostname, events);
    }
}

 

  • The above code creates an instance of EventGridClient and uses it to publish a list of EventGridEvent to the specified topic.
  •  

  • Remember to replace placeholders for topicEndpoint and accessKey with actual values from your Azure setup.

 

Handling Events

 

  • To process events, typically set up an Azure function or web API that subscribes to the Event Grid. Here's a basic handler in .NET Core:

 

using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.EventGrid.Models;
using Newtonsoft.Json;

[Route("api/[controller]")]
public class EventHandlerController : ControllerBase
{
    [HttpPost]
    public IActionResult HandleEvent([FromBody] EventGridEvent[] eventGridEvents)
    {
        foreach (var eventGridEvent in eventGridEvents)
        {
            if (eventGridEvent.EventType == "My.CustomEventType")
            {
                dynamic eventData = JsonConvert.DeserializeObject(eventGridEvent.Data.ToString());
                Console.WriteLine($"Received message: {eventData.Message}");
            }
        }

        return Ok();
    }
}

 

  • This endpoint receives event data, deserializes it, and processes it based on the event type.

 

Testing and Monitoring

 

  • Once integrated, you can test the end-to-end flow by triggering events manually from Azure or using tools like Postman to simulate event pushes.
  •  

  • Monitor your Event Grid using Azure Monitor to ensure messages are being successfully dispatched and received.