嘗試將檔案上傳到 Blob 存盤時出現此錯誤。當我在 localhost 上運行和在 Azure Function 中運行時,都會出現該錯誤。
我的連接字串看起來像: DefaultEndpointsProtocol=https;AccountName=xxx;AccountKey=xxx;EndpointSuffix=core.windows.net
未以正確格式提供身份驗證資訊。檢查 Authorization 標頭的值。時間:2021-10-14T15:56:26.7659660Z 狀態:400(認證資訊的格式不正確。檢查授權頭的值。)錯誤代碼:InvalidAuthenticationInfo
但這曾經在過去有效,但最近它開始為我創建的新存盤帳戶拋出此錯誤。我的代碼如下所示
public AzureStorageService(IOptions<AzureStorageSettings> options)
{
_connectionString = options.Value.ConnectionString;
_containerName = options.Value.ImageContainer;
_sasCredential = new StorageSharedKeyCredential(options.Value.AccountName, options.Value.Key);
_blobServiceClient = new BlobServiceClient(new BlobServiceClient(_connectionString).Uri, _sasCredential);
_containerClient = _blobServiceClient.GetBlobContainerClient(_containerName);
}
public async Task<string> UploadFileAsync(IFormFile file, string location, bool publicAccess = true)
{
try
{
await _containerClient.CreateIfNotExistsAsync(publicAccess
? PublicAccessType.Blob
: PublicAccessType.None);
var blobClient = _containerClient.GetBlobClient(location);
await using var fileStream = file.OpenReadStream();
// throws Exception here
await blobClient.UploadAsync(fileStream, true);
return blobClient.Uri.ToString();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
// To be able to do this, I have to create the container client via the blobService client which was created along with the SharedStorageKeyCredential
public Uri GetSasContainerUri()
{
if (_containerClient.CanGenerateSasUri)
{
// Create a SAS token that's valid for one hour.
var sasBuilder = new BlobSasBuilder()
{
BlobContainerName = _containerClient.Name,
Resource = "c"
};
sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(1);
sasBuilder.SetPermissions(BlobContainerSasPermissions.Write);
var sasUri = _containerClient.GenerateSasUri(sasBuilder);
Console.WriteLine("SAS URI for blob container is: {0}", sasUri);
Console.WriteLine();
return sasUri;
}
else
{
Console.WriteLine(@"BlobContainerClient must be authorized with Shared Key
credentials to create a service SAS.");
return null;
}
}
uj5u.com熱心網友回復:
請更改以下代碼行:
_blobServiceClient = new BlobServiceClient(new BlobServiceClient(_connectionString).Uri, _sasCredential);
到
_blobServiceClient = new BlobServiceClient(_connectionString);
考慮到您的連接字串具有所有必要的資訊,您實際上不需要做所有正在做的事情,您將使用BlobServiceClient(String)期望并接受連接字串的建構式。
您還可以洗掉以下代碼行:
_sasCredential = new StorageSharedKeyCredential(options.Value.AccountName, options.Value.Key);
如果它們不在其他地方使用,AccountName并且可能可以擺脫和擺脫Key您的配置設定。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/319016.html
