【发布时间】:2020-10-05 20:32:29
【问题描述】:
我很难弄清楚如何使用 .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");
}
}
【问题讨论】:
-
如果我理解正确,您可能希望使用 SAS URI 下载 blob。正确的?另外,
blobUri参数是什么?它是 blob 的名称还是它的 URL? -
如果您已经拥有帐户密钥,为什么要生成 SAS 令牌?为什么不直接使用密钥下载?
-
@GauravMantri-AIS,正确。而 blobUri 参数是博客 URL。
-
@silent,我不知道如何使用帐户密钥下载文件?此外,这只是一个 POC,我最终会从源代码中删除这个密钥,我想使用 SAS 令牌作为更安全的方式
-
Sam...您无法真正摆脱帐户密钥,因为它是生成 SAS 令牌所必需的。
标签: azure azure-storage azure-blob-storage azure-sdk-.net