Sajeetharan 的回答让我寻找一个实际存在的BlobSasBuilder类。
以下是我如何在服务器上构建一个:
// Creates a client to the BlobService using the connection string.
var blobServiceClient = new BlobServiceClient(storageConnectionString);
// Gets a reference to the container.
var blobContainerClient = blobServiceClient.GetBlobContainerClient(<ContainerName>);
// Gets a reference to the blob in the container
BlobClient blobClient = containerClient.GetBlobClient(<BlobName>);
// Defines the resource being accessed and for how long the access is allowed.
var blobSasBuilder = new BlobSasBuilder
{
StartsOn = DateTime.UtcNow.Subtract(clockSkew),
ExpiresOn = DateTime.UtcNow.Add(accessDuration) + clockSkew,
BlobContainerName = <ContainerName>,
BlobName = <BlobName>,
};
// Defines the type of permission.
blobSasBuilder.SetPermissions(BlobSasPermissions.Write);
// Builds an instance of StorageSharedKeyCredential
var storageSharedKeyCredential = new StorageSharedKeyCredential(<AccountName>, <AccountKey>);
// Builds the Sas URI.
BlobSasQueryParameters sasQueryParameters = blobSasBuilder.ToSasQueryParameters(storageSharedKeyCredential);
以下是如何在客户端使用它:
// Builds the URI to the blob storage.
UriBuilder fullUri = new UriBuilder()
{
Scheme = "https",
Host = string.Format("{0}.blob.core.windows.net", <AccountName>),
Path = string.Format("{0}/{1}", <ContainerName>, <BlobName>),
Query = sasQueryParameters.ToString()
};
// Get an instance of BlobClient using the URI.
var blobClient = new BlobClient(fullUri.Uri, null);
// Upload stuff in the blob.
await blobClient.UploadAsync(stream);
附录
正如@one2012 在评论中提到的那样,在这个答案之后几个月后,一个页面已经出现,展示了 Azure.Storage 命名空间中的所有功能。该链接可用于获取更多信息。
更新
在服务器端,我有一个 Azure 函数,它现在将 Azure 存储与函数的托管标识连接起来。当我连接存储时,我不再使用帐户,只使用存储的端点:
BlobContainerClient blobContainerClient = new(new Uri(containerEndpoint), new DefaultAzureCredential());
这使得初始服务器代码的以下部分有点棘手,因为我曾经使用该CloudStorageAccount.Credentials.GetExportKeys()
方法来获取帐户的密钥。使用托管身份时,我似乎无法再访问它了:
// Builds an instance of StorageSharedKeyCredential
var storageSharedKeyCredential = new StorageSharedKeyCredential(<AccountName>, <AccountKey>);
事实证明,我必须使用用户委派来构建 SAS Uri:
...
BlobServiceClient blobServiceClient = blobClient.GetParentBlobContainerClient().GetParentBlobServiceClient();
UserDelegationKey userDelegationKey = await blobServiceClient.GetUserDelegationKeyAsync
(
DateTimeOffset.UtcNow,
DateTimeOffset.UtcNow.AddMinutes(5d)
);
BlobUriBuilder blobUriBuilder = new (blobClient.Uri)
{
// Specify the user delegation key.
Sas = blobSasBuilder.ToSasQueryParameters(userDelegationKey, blobServiceClient.AccountName)
};
string uri = blobUriBuilder.ToUri();