使用SAS从Azure存储下载blob

时间:2020-06-16 09:12:37

标签: azure azure-storage azure-storage-blobs azure-sdk-.net

我很难弄清楚如何使用.net和生成的Shared Access Signature令牌从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");
        }

    }

1 个答案:

答案 0 :(得分:0)

在官方github回购中,您可以找到使用各种身份验证方法的出色示例。使用sample is called SharedKey中的帐户密钥。还有一个sample to use SAS tokens-但您需要以某种方式生成它们。通常,您使用帐户密钥执行此操作...

另一个选择-如果可能的话,我建议使用AAD (Azure Active Directory)-based aut h。在这种情况下,您不需要帐户密钥或SAS令牌。

有关各种示例,请参见此处: https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/storage/Azure.Storage.Blobs/samples/Sample02_Auth.cs