首页 > 解决方案 > Download blob from Azure Storage with SAS

问题描述

I am having a hard time figuring out how to download a blob from Azure storage using .net and a generated Shared Access Signature token.

First of all, most of the tutorials I could find are using Microsoft.Azure.Management.Storage nuget package, which is deprecated. Instead I use the newest Azure.Storage.Blobs package.

I have the following code so far. I don't know what to do with the generated SAS token. How do I download the blob from there ?

  [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");
        }

    }

标签: azureazure-storageazure-blob-storageazure-sdk-.net

解决方案


在官方 github 存储库中,您可以找到使用各种身份验证方式的绝佳示例。在示例中使用帐户密钥称为 SharedKey。还有一个使用 SAS 令牌的示例- 但您需要以某种方式生成这些令牌。通常您使用帐户密钥执行此操作...

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

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


推荐阅读