用SAS从Azure存储下载blob

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

我很难搞清楚如何使用 .net 和生成的共享访问签名令牌从 Azure 存储下载 blob。

首先,我找到的大多数教程都是使用 Microsoft.Azure.Management.Storage nuget包,它已经被废弃了。相反,我使用最新的 Azure.Storage.Blobs 包。

到目前为止,我有以下代码。我不知道该如何处理生成的SAS令牌。我如何从那里下载blob?

  [HttpGet]
    public async Task<IActionResult> Download([FromQuery] string blobUri)
    {
        BlobServiceClient blobServiceClient = new BlobServiceClient(this.configuration.GetConnectionString("StorageAccount"));


        // Create a SAS token that's valid for one hour.
        BlobSasBuilder sasBuilder = new BlobSasBuilder()
        {
            BlobContainerName = "my container name",
            BlobName = blobUri,
            Resource = "b",
            StartsOn = DateTimeOffset.UtcNow,
            ExpiresOn = DateTimeOffset.UtcNow.AddHours(1)
        };

        // Specify read permissions for the SAS.
        sasBuilder.SetPermissions(BlobSasPermissions.Read);

        // Use the key to get the SAS token.
        var sasToken = sasBuilder.ToSasQueryParameters(new Azure.Storage.StorageSharedKeyCredential("my account name", "my account key"));



        BlobClient blob = blobServiceClient.GetBlobContainerClient("my container name").GetBlobClient($"{blobUri}");
        await using (MemoryStream memoryStream = new MemoryStream())
        {
            await blob.DownloadToAsync(memoryStream);
           return File(memoryStream, "file");
        }

    }
azure azure-storage azure-storage-blobs azure-sdk-.net
1个回答
0
投票

在官方的github repo中,你会发现使用各种认证手段的伟大的例子。使用帐户密钥在 样本叫做SharedKey. 还有一个 使用SAS令牌的样本 - 但那些你需要以某种方式生成。通常情况下,你会使用账户密钥来做这件事... ...

另一个选择--如果可能的话,我建议使用的是使用 基于AAD(Azure Active Directory)的自动识别功能。h. 在这种情况下,你既不需要账户密钥,也不需要SAS令牌。

请看这里的各种样本。https:/github.comAzureazure-sdk-for-netblobmastersdkstorageAzure.Storage.BlobssamplesSample02_Auth.cs。

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