In my application made with asp.net core, I have a page that allow user to add & remove 3 images for their product. When the user add an image, I upload it to Azure Blob Storage with a specific name ( from 3 variables ).
But if the user delete and add one of this image, the image still the same because of cache and because I keep the same name. I don't want to change the file name to avoid managing the deletion in Azure Blob Storage.
Here the code of the upload method :
public async Task<string> UploadFileToCloudAsync(string containerName, string name, Stream file)
{
var cloudBlobContainerClient = await StorageHelper.ConnectToBlobStorageAsync(_blobStorageEndPoint, containerName);
if (cloudBlobContainerClient == null)
{
throw new NullReferenceException($"Unable to connect to blob storage {name}");
}
BlobClient blobClient = cloudBlobContainerClient.GetBlobClient(name);
await blobClient.UploadAsync(file, true);
var headers = await CreateHeadersIfNeededAsync(blobClient);
if (headers != null)
{
// Set the blob's properties.
await blobClient.SetHttpHeadersAsync(headers);
}
return blobClient.Uri.AbsoluteUri;
}
Here's the method to create the headers:
private readonly string _defaultCacheControl = "max-age=3600, must-revalidate";
private async Task<BlobHttpHeaders> CreateHeadersIfNeededAsync(BlobClient blobClient)
{
BlobProperties properties = await blobClient.GetPropertiesAsync();
BlobHttpHeaders headers = null;
if (properties.CacheControl != _defaultCacheControl)
{
headers = new BlobHttpHeaders
{
// Set the MIME ContentType every time the properties
// are updated or the field will be cleared
ContentType = properties.ContentType,
ContentLanguage = properties.ContentLanguage,
CacheControl = _defaultCacheControl,
ContentDisposition = properties.ContentDisposition,
ContentEncoding = properties.ContentEncoding,
ContentHash = properties.ContentHash
};
}
return headers;
}
I need to know if is possible to force cache to be invalidated? I think with the cache invalidation, the correct image should be displayed after an add/delete/add for the same image.
If you want to reuse the same name for different content, you'd need to prevent caching using Cache-Control: no-cache
. Specifying must-revalidate
only causes validation after the validity period.
It's worth noting that this is bad for clients and servers because you lose all caching. Much better to use unique names and design for immutability of assets.