Skip to content

Instantly share code, notes, and snippets.

@xtellurian
Created October 27, 2017 00:26
Show Gist options
  • Save xtellurian/1ee357452668d7c3f46b83410c84435c to your computer and use it in GitHub Desktop.
Save xtellurian/1ee357452668d7c3f46b83410c84435c to your computer and use it in GitHub Desktop.
An ASP.NET Api Controller for Azure Event Grid Webhooks
using Newtonsoft.Json.Linq;
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
namespace MyApp.Api.Controllers
{
public class EventsController : ApiController
{
public EventsController(){}
public async Task<HttpResponseMessage> Post([FromBody]dynamic e)
{
// WARNING - this endpoint needs to be protected by a secret key.
// the key should be included as a URL parameter i.e. http://<endpoint>/api/events?key=YOUR_SECRET_KEY
// this code is for registering the webhook by returning a validation code
// I know, it looks weird, iterating though a dynamic -- its because of the structure of the body
// https://docs.microsoft.com/en-us/azure/event-grid/security-authentication
foreach ( var azEvent in e)
{
if (azEvent?.data?.validationCode != null)
{
// return the validation code to prove we own this server
// this code will only be called once, when the event subscription occurs.
// if this code is removed, then the subscription creation will fail
return Request.CreateResponse(HttpStatusCode.OK, new { validationResponse = x.data.validationCode });
}
else
{
var jObj = azEvent as JObject; // cast as JObject
var azE = jObj.ToObject<AzureEvent>(); // cast to Azure Event
if (azE != null) await HandleEvent(azE);
}
}
return Request.CreateResponse(HttpStatusCode.OK);
}
private async Task HandleEvent(AzureEvent azE)
{
// handle the event here.
// You should probably use Task.Factory.StartNew(...) so that we return from the controller method asap
}
// the structure of an Event
public class AzureEvent
{
public string id { get; set; }
public string topic { get; set; }
public string subject { get; set; }
public dynamic data { get; set; }
public string eventType { get; set; }
public DateTime eventTime { get; set; }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment