【问题标题】:.NET & Azure Blob Storage - Force cache invalidation for same name image.NET 和 Azure Blob 存储 - 对同名图像强制缓存失效
【发布时间】:2021-06-24 19:29:28
【问题描述】:

在我使用 asp.net 核心制作的应用程序中,我有一个页面允许用户为他们的产品添加和删除 3 个图像。 当用户添加图像时,我使用特定名称(来自 3 个变量)将其上传到 Azure Blob 存储。

但是如果用户删除并添加了一张图片,由于缓存和我保持相同的名称,图片仍然相同。我不想更改文件名以避免管理 Azure Blob 存储中的删除。

这里是上传方法的代码:

 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;
        }
```

and here 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 invalidate ? I think with the cache invalidation, the correct image should be displayed after an add / delete / add for the same image.

Thanks in advance

【问题讨论】:

    标签: c# asp.net asp.net-core azure-blob-storage


    【解决方案1】:

    如果您想为不同的内容重复使用相同的名称,您需要使用Cache-Control: no-cacheprevent caching。指定must-revalidate 只会在有效期后进行验证。

    值得注意的是,这对客户端和服务器不利,因为您会丢失所有缓存。更好地使用独特的名称和设计来实现资产的不变性。

    【讨论】:

    • 经过几周的测试,这似乎完美无缺。谢谢
    猜你喜欢
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    • 2018-07-11
    • 1970-01-01
    • 2020-04-15
    • 2011-09-24
    • 2016-08-15
    相关资源
    最近更新 更多