Add Cache-Control and Expires headers to Azure Storage Blobs

前端 未结 8 1715
刺人心
刺人心 2020-12-04 21:48

I\'m using Azure Storage to serve up static file blobs but I\'d like to add a Cache-Control and Expires header to the files/blobs when served up to reduce bandwidth costs.

8条回答
  •  执笔经年
    2020-12-04 22:11

    Here's an updated version of Joel Fillmore's answer consuming WindowsAzure.Storage v9.3.3. Note that ListBlobsSegmentedAsync returns a page size of 5,000 which is why the BlobContinuationToken is used.

        public async Task BackfillCacheControlAsync()
        {
            var container = await GetCloudBlobContainerAsync();
            BlobContinuationToken continuationToken = null;
    
            do
            {
                var blobInfos = await container.ListBlobsSegmentedAsync(string.Empty, true, BlobListingDetails.None, null, continuationToken, null, null);
                continuationToken = blobInfos.ContinuationToken;
                foreach (var blobInfo in blobInfos.Results)
                {
                    var blockBlob = (CloudBlockBlob)blobInfo;
                    var blob = await container.GetBlobReferenceFromServerAsync(blockBlob.Name);
                    if (blob.Properties.CacheControl != "public, max-age=31536000")
                    {
                        blob.Properties.CacheControl = "public, max-age=31536000";
                        await blob.SetPropertiesAsync();
                    }
                }               
            }
            while (continuationToken != null);
        }
    
        private async Task GetCloudBlobContainerAsync()
        {
            var storageAccount = CloudStorageAccount.Parse(_appSettings.AzureStorageConnectionString);
            var blobClient = storageAccount.CreateCloudBlobClient();
            var container = blobClient.GetContainerReference("uploads");
            return container;
        }
    

提交回复
热议问题