Using Azure Event Grid to generate and consume events

Using Azure Event Grid to generate and consume events


Summary

In today’s article we will look at how we can use Azure’s Event Grid to pass events from one application or resource to another. Unlike queues or service bus, the Event Grid will push the events once generated to the subscriber. The subscriber does not have to poll or pull these events.

?

Scenario

We will create an Azure Event Grid Topic. Then, we will create a C# console application to generate an event. Finally, we will create an ASP.NET controller action which will subscribe to the event topic and when an event is received, it will process it.

?

Step 1. Create the Event Grid Topic in Azure

1. Log in to the Azure Portal.

2. Create Event Grid Topic.

3. Configure and create the resource.

Write down the "Topic Endpoint" and "Access Key" after creation, you'll need them later.

?

Step 2. Create a .NET 6 C# Console Application to Publish an Event

Create a .NET console application and replace the code in the “Program.cs” file as below:

using System;
    using Azure.Messaging.EventGrid;
    using System.Threading.Tasks;

    class Program
    {
        static async Task Main(string[] args)
        {
            string topicEndpoint = "YOUR_TOPIC_ENDPOINT";
            string topicKey = "YOUR_ACCESS_KEY";

            EventGridPublisherClient client = new EventGridPublisherClient(new Uri(topicEndpoint), new AzureKeyCredential(topicKey));
            await client.SendEventAsync(new EventGridEvent(
                "Subject",
                "EventType",
                "1.0",
                "This is an example message"
            ));
            Console.WriteLine("Event has been published.");
        }
    }        

Replace YOUR_TOPIC_ENDPOINT and YOUR_ACCESS_KEY with your Event Grid Topic endpoint and access key respectively.

?

Step 3. Create the ASP.NET Web API controller and action

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Azure.Messaging.EventGrid;
using Microsoft.Extensions.Logging;

namespace EventGridReceiverAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EventGridController : ControllerBase
    {
        private readonly ILogger<EventGridController> _logger;
        public EventGridController(ILogger<EventGridController> logger)
        {
            _logger = logger;
        }
        [HttpPost]
        public async Task<IActionResult> ReceiveEvent([FromBody] object events)
        {
            try
            {
                // Parse received events
                List<EventGridEvent> eventGridEvents = EventGridEvent.ParseMany(new BinaryData(events));
                foreach (EventGridEvent eventGridEvent in eventGridEvents)
                {
                    // Handle the event
                    _logger.LogInformation($"Event received. Event Type: {eventGridEvent.EventType}");
                    // If the event subject to subscription validation, send back the validation code
                    if (eventGridEvent.EventType == "Microsoft.EventGrid.SubscriptionValidationEvent")
                    {
                        var eventData = eventGridEvent.GetData<Dictionary<string, string>>();
                        if (eventData.ContainsKey("validationCode"))
                        {
                            var validationCode = eventData["validationCode"];
                            return Ok(new { validationResponse = validationCode });
                        }
                    }
                    // Add your logic to process the event
                }
                return Ok();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error processing events");
                return StatusCode(500);
            }
        }
    }
}        

Step 4. Set the ASP.NET application to subscribe to the Event Grid Topic in Azure

1. Go to your Event Grid Topic in Azure Portal. 2. Create a new Event Subscription. 3. For "Endpoint Type", choose "Web Hook".

4. Enter the URL of your deployed Web API, pointing to the new controller action (e.g., https://your-api-domain/api/eventgrid).

?

Step 5. Test the solution. Once deployed and configured, you should be able to receive Event Grid events in this Web API action. The controller logs incoming event types and sends back a validation code if Azure Event Grid is doing a handshake request.

?

Please note that if you are running the API locally, you will need to expose it to the internet for Azure Event Grid to be able to send events to it. After exposing your local API, use that public URL when setting up your Event Grid subscription.

?

Conclusion

In today’s article we looked at setting up Azure Event Grid topics and using these to send and receive events. This mechanism is useful in setting up disconnected services in a cloud environment.

要查看或添加评论,请登录

Munib Butt的更多文章

社区洞察

其他会员也浏览了