use*_*080 3 .net azure azure-storage azure-blob-storage azure-sas
我正在使用Azure.Storage.Blobs v12.1.0图书馆。我正在使用用户委托和 Azure 服务主体凭据生成 Blob 级 SAS 令牌,并尝试使用生成的 SAS 令牌上传 Blob。我完全按照Azure 中的此代码示例生成 SAS 令牌。
这是我用来创建 SAS 令牌的代码:
string blobEndpoint = string.Format("https://{0}.blob.core.windows.net", storageProviderSettings.AccountName);
TokenCredential credential =
new ClientSecretCredential(
storageProviderSettings.TenantId,
storageProviderSettings.ClientId,
storageProviderSettings.ClientSecret,
new TokenCredentialOptions());
BlobServiceClient blobServiceClient = new BlobServiceClient(new Uri(blobEndpoint),
credential);
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);
BlobClient blobClient = containerClient.GetBlobClient(blobName);
var delegationKey = await blobServiceClient.GetUserDelegationKeyAsync(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(7));
BlobSasBuilder sasBuilder = new BlobSasBuilder()
{
BlobContainerName = containerName,
BlobName = blobName,
Resource = "b",
StartsOn = DateTimeOffset.UtcNow,
ExpiresOn = DateTimeOffset.UtcNow.AddSeconds(expirySeconds)
};
sasBuilder.SetPermissions(BlobSasPermissions.All);
// if (withDownloadAccess) {
// sasBuilder.SetPermissions(BlobSasPermissions.Read);
// }
// if (withDeleteAccess) {
// sasBuilder.SetPermissions(BlobSasPermissions.Delete);
// }
Console.WriteLine(sasBuilder.Permissions);
var sasQueryParams = sasBuilder.ToSasQueryParameters(delegationKey, storageProviderSettings.AccountName).ToString();
UriBuilder sasUri = new UriBuilder()
{
Scheme = "https",
Host = string.Format("{0}.blob.core.windows.net", storageProviderSettings.AccountName),
Path = string.Format("{0}/{1}", containerName, blobName),
Query = sasQueryParams
};
BlobServiceClient service = new BlobServiceClient(sasUri.Uri);
await service.GetPropertiesAsync();
Settings tmpUploadCredentials = CreateTemporaryAzureStorageProviderSettings(sasUri, storageProviderSettings);
Console.WriteLine(tmpUploadCredentials.ConnectionString);
return tmpUploadCredentials;
Run Code Online (Sandbox Code Playgroud)
SAS 令牌已创建,并且如果我将其保留在浏览器中,则“获取 Blob”工作得非常好,但BlobServiceClient如果我尝试上传文件或执行它现在正在工作的任何操作,则使用“获取 Blob”。为了检查它是否经过身份验证,我编写了此行await service.GetPropertiesAsync();,该行引发以下错误:
任何帮助将不胜感激。
根据我的测试,service.GetPropertiesAsync();是对帐户的操作。这意味着它将调用Get Blob Service Properties Rest api 来获取帐户的 Blob 服务的属性。但是,当您创建 时BlobServiceClient,您需要提供 blob url。Blob 不支持该操作。所以你会得到错误。它想要获取 blob 的属性,请调用api。因此,请按照以下代码更新您的代码
BlobClient blobClient = new BlobClient(sasUri, null);
blobClient.GetPropertiesAsync();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6338 次 |
| 最近记录: |