I’m storing my blog’s images in Azure storage and serve them via Azure CDN for a better performance. However, the images didn’t have a Cache-Control header so far, so they wouldn’t get cached as much / as long as I wanted to. And while setting the CacheControl property on my Azure Storage blobs manually is possible, I didn’t want to do that, but rather have it automated. Azure and automation? Functions to the rescue!
First of all, my Storage account contains a container named blog, in which I’ve got all relevant images stored:
To get started, I created a new Function with the BlobTrigger – C# template:
I changed the path from the provided samples-workitems to blog (my container), and selected the appropriate Storage account.
This is the corresponding function.json that was created for me:
{ "bindings": [ { "name": "myBlob", "type": "blobTrigger", "direction": "in", "path": "blog/{name}", "connection": "myStorageAccount_STORAGE" } ], "disabled": false }
For my code, I had to make some small changes only. First of all, I added a reference to the Microsoft.WindowsAzure.Storage package. I also created a variable named newCacheSettings that defines the default value I want to use for my CacheControl property (I set it to 3 months here). Lastly, within my Run function, I simply check the value of the CacheControl property of the triggering blob, and if it differs from my default value, I update it.
Please note that I’m using Block Blobs, so Append Blobs and Page Blobs won’t get updated by the code below.
#r "Microsoft.WindowsAzure.Storage" using Microsoft.WindowsAzure.Storage.Blob; private static string newCacheSettings = "public, max-age=7776000"; // 3 months public static void Run(CloudBlockBlob myBlob, string name, TraceWriter log) { log.Info($"C# Blob trigger function Processed blob\n Cache:{myBlob.Properties.CacheControl}"); // only set the cache control property if it differs (e.g., if it is empty) if(myBlob.Properties.CacheControl != newCacheSettings) { myBlob.Properties.CacheControl = newCacheSettings; myBlob.SetProperties(); log.Info($"New Cache:{myBlob.Properties.CacheControl}"); } }
That’s it! Just a few lines of code, and once again Functions has simplified a manual task for me.
Automatically setting Cache-Control for Azure Storage Blobs via Azure Functions https://t.co/xb1UYp4j0k #azure #azurefunctions
Automatically setting Cache-Control for Azure Storage Blobs via Azure Functions – Rene Modery… https://t.co/8hAJlTjDSm