The scenario: while uploading (media) files to Azure Storage (containers), we can use Event Grid to manage the Storage events (Add, Update, Delete) and use an Azure Function as event handler for file processing upon events.
Even though an Azure Function with Blob trigger can monitor such events, it works only for a single specific container instead of any containers on a storage account hence not applicable for this scenario.
And we would like to use Visual Studio to develop such a function. Currently Visual Studio does not yet allow you to create an function with Event Grid trigger, so we have to use HTTP trigger.
The steps:
- Create an Azure Function in Visual Studio with HTTP trigger (code below) and publish to the same resource group and region as the storage;
- In Azure portal, get the function endpoint URL of the above published Azure Function;
- Go to the Azure Storage account you want to monitor in Azure portal, click Event Grid and add an Event Subscription to the storage. For the text box with the label “Subscriber Endpoint”, put in the function endpoint URL from step 2.
With these steps, you have both a topic and subscription for the storage and the Function as event handler.
public static class Function1
{
[FunctionName("StorageEventFunction")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
string jsonContent = await req.Content.ReadAsStringAsync();
dynamic eventgridinfo = JsonConvert.DeserializeObject(jsonContent);
log.Info($"function trigger with data: {eventgridinfo}");
var eventType = eventgridinfo[0].eventType.ToString();
var imageUrl = eventgridinfo[0].data.url.ToString();
log.Info($"triggering with event {eventType} and url {imageUrl}");
switch (eventType)
{
case "Microsoft.Storage.BlobCreated":
log.Info("BlobCreated");
break;
case "Microsoft.Storage.BlobDeleted":
log.Info("BlobDeleted");
break;
default:
throw new ArgumentException($"unsupported event type: {eventType}");
}
return req.CreateResponse(HttpStatusCode.OK);
}
}