更改 CDN Blob 存储 ASP.NET 中的文件内容后刷新缓存

问题描述 投票:0回答:1

有什么方法可以通过 .NET 使用 CDN 更改 azure 存储帐户中的缓存控制吗?

我有 UploadFilesAsync 方法,该方法将新文件上传到 blob 存储中,并且此方法还更新同名文件的内容。

问题是,当我更新文件内容时,CDN 端点返回缓存的旧内容。

我的想法是,我将缓存控制设置为10秒,然后缓存内容刷新为实际内容,但它不起作用。

在天蓝色门户中,我看到缓存控制已设置,但缓存内容未刷新

我能做什么?谢谢。

我的UploadFilesAsync方法

public async Task<ImageInfoDto> UploadFilesAsync(string fileName, Stream fileStream, string contentType, bool isUpdated)
    {
        try
        {
            var storageAccount =
                CloudStorageAccount
                    .Parse(_configuration["StorageAccountConnectionString"]);

            var blobClient = storageAccount.CreateCloudBlobClient();

            var container =
                blobClient.GetContainerReference(_configuration["BlobStorageContainerName"]);

            var cdnEndpoint = _configuration["CdnEndpoint"];

            var blob = container.GetBlockBlobReference(fileName);

            using var ms = new MemoryStream();

            fileStream.Position = 0;
            await fileStream.CopyToAsync(ms);
            ms.Position = 0;
            await blob.UploadFromStreamAsync(ms);

            if (isUpdated)
            {
                blob.Properties.CacheControl = "s-maxage=10";
            }

            blob.Properties.ContentType = contentType;

            await blob.SetPropertiesAsync();

            return new ImageInfoDto
            {
                StorageUrl = blob.Uri.ToString(),
                CdnUrl = cdnEndpoint + "/" + container.Name + "/" + fileName,
                ContentType = contentType
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed");
        }
    }
c# azure azure-blob-storage blob cdn
1个回答
0
投票

CDN 在更新 Azure Blob 存储中的文件时不刷新缓存内容可能是由于 CDN 的缓存设置造成的。在 blob 对象上设置

CacheControl
属性是正确的,但 CDN 可能有自己的缓存配置,从而影响行为。

要在更新文件内容时强制 CDN 刷新其缓存,可以使用缓存清除技术。一种常见的方法是在请求文件时将唯一的查询参数附加到 URL。这使得 CDN 将请求视为新请求并获取文件的最新版本。

enter image description here

using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;

public class ImageService
{
    private readonly IConfiguration _configuration;
    private readonly ILogger<ImageService> _logger;

    public ImageService(IConfiguration configuration, ILogger<ImageService> logger)
    {
        _configuration = configuration;
        _logger = logger;
    }

    public async Task<ImageInfoDto> UploadFileAsync(string localFilePath, string fileName, string contentType, bool isUpdated)
    {
        try
        {
            // Get configuration values
            string? storageConnectionString = _configuration["StorageConnectionString"];
            string? blobContainerName = _configuration["BlobContainerName"];
            string? cdnEndpoint = _configuration["CdnEndpoint"];

            if (string.IsNullOrWhiteSpace(storageConnectionString) || string.IsNullOrWhiteSpace(blobContainerName) || string.IsNullOrWhiteSpace(cdnEndpoint))
            {
                throw new InvalidOperationException("Configuration values are missing or empty.");
            }

            var storageAccount = CloudStorageAccount.Parse(storageConnectionString);
            var blobClient = storageAccount.CreateCloudBlobClient();
            var container = blobClient.GetContainerReference(blobContainerName);

            var blob = container.GetBlockBlobReference(fileName);

            using (var fileStream = File.OpenRead(localFilePath))
            {
                await blob.UploadFromStreamAsync(fileStream);
            }

            if (isUpdated)
            {
                // Append a cache-busting query parameter to the URL
                var uniqueQueryParam = $"cb={Guid.NewGuid()}";
                var cdnUrl = $"{cdnEndpoint}/{container.Name}/{fileName}?{uniqueQueryParam}";
                return new ImageInfoDto
                {
                    StorageUrl = blob.Uri.ToString(),
                    CdnUrl = cdnUrl,
                    ContentType = contentType
                };
            }

            blob.Properties.ContentType = contentType;
            await blob.SetPropertiesAsync();

            return new ImageInfoDto
            {
                StorageUrl = blob.Uri.ToString(),
                CdnUrl = $"{cdnEndpoint}/{container.Name}/{fileName}",
                ContentType = contentType
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed");
            throw;
        }
    }

    public class ImageInfoDto
    {
        public string? StorageUrl { get; set; }
        public string? CdnUrl { get; set; }
        public string? ContentType { get; set; }
    }
}

class Program
{
    static async Task Main(string[] args)
    {
        // Configuration values (replace with your actual values)
        string? storageConnectionString = "";
        string? blobContainerName = "";
        string? cdnEndpoint = " ";

        // Create configuration
        var configuration = new ConfigurationBuilder()
            .AddInMemoryCollection(new[]
            {
                new KeyValuePair<string, string?>("StorageConnectionString", storageConnectionString),
                new KeyValuePair<string, string?>("BlobContainerName", blobContainerName),
                new KeyValuePair<string, string?>("CdnEndpoint", cdnEndpoint)
            })
            .Build();

        // Create logger (you can configure it as needed)
        var loggerFactory = LoggerFactory.Create(builder =>
        {
            builder.AddConsole();
        });
        var logger = loggerFactory.CreateLogger<ImageService>();

        // Create ImageService with the configuration and logger
        var imageService = new ImageService(configuration, logger);

        // Example usage
        string localFilePath = " ";
        string fileName = "sample1.jpg";
        string contentType = "image/jpeg";
        bool isUpdated = false;

        try
        {
            var imageInfo = await imageService.UploadFileAsync(localFilePath, fileName, contentType, isUpdated);
            Console.WriteLine($"Storage URL: {imageInfo.StorageUrl}");
            Console.WriteLine($"CDN URL: {imageInfo.CdnUrl}");

            Console.ReadLine();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

输出: enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.