【问题标题】:How to add authentication to Azure storage blob upload如何向 Azure 存储 Blob 上传添加身份验证
【发布时间】:2021-06-03 04:55:18
【问题描述】:

我正在尝试将图像上传到 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. 除外。我说可预测是因为我没有添加任何身份验证...

这就是问题/问题。如何添加身份验证以便上传?

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

感谢任何见解。

【问题讨论】:

    标签: c# azure authentication blob azure-storage


    【解决方案1】:

    如果您有权访问 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

    【讨论】:

    • 这正是我所需要的!谢谢你的帮助:o)
    【解决方案2】:

    您应该通过 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);
    

    【讨论】:

    • 如果我没记错的话,上面的代码是针对旧版 SDK 而不是 OP 使用的 12.8.0 版本。
    • 感谢您的快速回答,但@GauravMantri 是正确的,不幸的是这是旧版本
    猜你喜欢
    • 2017-03-01
    • 1970-01-01
    • 2020-08-06
    • 2021-07-05
    • 2017-11-04
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    相关资源
    最近更新 更多