如何向 Azure 存储 blob 上传添加身份验证

How to add authentication to Azure storage blob upload

我正在尝试将图像上传到 Azure Blob 存储。我正在使用 .Net Core 和 Azure.Storage.Blobs v12.8.0.

下面的代码是我目前的代码。

try
    {
    var documentByteArray = // a valid byte array of a png file
    var blobUri = new Uri("https://mystorageaccount.blob.core.windows.net/images/myfile.png");

    BlobClient blobClient = new BlobClient(blobUri);

    using (MemoryStream stream = new MemoryStream(documentByteArray))
    {
        await blobClient.UploadAsync(stream, true, default);
        await blobClient.SetHttpHeadersAsync(new BlobHttpHeaders
        {
            ContentType = "image/png"
        });
    }
}
catch (Exception ex)
{
    //
}

...但可以预见的是它失败了 Server failed to authenticate the request. Please refer to the information in the www-authenticate header.。我说可预测是因为我没有添加任何身份验证...

这是problem/question。如何添加身份验证以便上传?

我知道我可以使用访问密钥 - 但如何使用?我在 MS 文档中找不到任何示例。

如有任何见解,我们将不胜感激。

您应该通过 CloudStorageAccount 实例上传您的 blob,如下所示:

var storageAccount = new CloudStorageAccount(
    new StorageCredentials("<your account name>", "<your key>"),
    "core.windows.net",
    true);

var blobClient = storageAccount.CreateCloudBlobClient();

var container = blobClient.GetContainerReference(containerName);

var blob = container.GetBlockBlobReference(fileName);

await blob.UploadFromStreamAsync(stream);

如果您有权访问 Azure 门户,则可以获得存储帐户的连接字符串(在“访问密钥”部分下)。

获得连接字符串后,您可以使用以下代码:

var connectionString = "your-storage-account-connection-string";
var containerName = "images";
var blobName = "myfile.png";

var blobClient = new BlobClient(connectionString, containerName, blobName);
//do the upload here...

其他选项是使用存储帐户名称和访问密钥(您同样可以从 Azure 门户获取)。你会做这样的事情:

var accountName = "account-name";
var accountKey = "account-key";
var blobUri = new Uri("https://mystorageaccount.blob.core.windows.net/images/myfile.png");
var credentials = new StorageSharedKeyCredential(accountName, accountKey);
var blobClient = new BlobClient(blobUri, credentials);
//do the upload here...

您可以在此处找到有关 BlobClient 构造函数的更多信息:https://docs.microsoft.com/en-us/dotnet/api/azure.storage.blobs.blobclient?view=azure-dotnet