适用于 .NET 的 Azure Blob 存储 SDK BlobClient.UploadAsync 总是抛出异常但总是上传文件

Azure Blob Storage SDK for .NET BlobClient.UploadAsync always throws exception but always uploads the file

所以最近我看到 Microsoft.Azure.Storage 已被弃用并开始迁移到新的 Azure.Blob.Storage SDK。除了每次上传都会抛出异常的 UploadAsync 方法外,一切都运行良好。

我收到 409 The specified blob already exists 错误。但我 100% 确定 blob 不存在,因为它总是使用 GUID 上传并在上传方法之前添加断点并从 blobstorage 获取 BlobClient url 始终 returns XML这个 blob 不存在。

抛出错误,但我的文件总是上传。我不需要 overwrite: true 标志,因为它总是新的。

这是一些示例代码:

public async Task StoreAsync(
        string container,
        string blob,
        byte[] givenBytes,
        CancellationToken cancellationToken = default)
    {
        BlobContainerClient containerReference = this.client.GetBlobContainerClient(container);
        await containerReference.CreateIfNotExistsAsync();
        BlobClient blobReference = containerReference.GetBlobClient(blob);

        cancellationToken.ThrowIfCancellationRequested();

        await blobReference.UploadAsync(new BinaryData(givenBytes), CancellationToken.None);
    }

请注意,字符串 blob 参数始终是来自其他地方的 GUID。

这是完整的class:

public class CustomBlobStore : IBlobStore
{
    private BlobServiceClient client;

    public CustomBlobStore(string accountName, string accountKey)
    {
        this.client = new BlobServiceClient(CreateBlobStoreConnectionString(accountName, accountKey));
    }

    private static string CreateBlobStoreConnectionString(string accountName, string accountKey)
    {
        return "DefaultEndpointsProtocol=https;AccountName=" + accountName + ";AccountKey=" + accountKey;
    }

    public async Task StoreAsync(
        string container,
        string blob,
        byte[] givenBytes,
        CancellationToken cancellationToken = default)
    {
        BlobContainerClient containerReference = this.client.GetBlobContainerClient(container);
        await containerReference.CreateIfNotExistsAsync();
        BlobClient blobReference = containerReference.GetBlobClient(blob);

        cancellationToken.ThrowIfCancellationRequested();

        await blobReference.UploadAsync(new BinaryData(givenBytes), CancellationToken.None);
    }
}

函数调用方式(附件可以是任何类型的文件):

public async Task<ActionResult> SaveFile(IEnumerable<HttpPostedFileBase> files)
{
    var file = files.First();
    byte[] fileData;
    using (var ms = new MemoryStream())
    {
        file.InputStream.CopyTo(ms);
        fileData = ms.ToArray();
    }
    
    StoreAttachmentAsync(Guid.NewGuid(),fileData);
}

private Task StoreAttachmentAsync(string name, byte[] attachment)
    {
        return this.customBlobStore.StoreAsync('/attachments', name, attachment);
    }

问题出在一些基础程序集中,这些程序集在不同项目中存在版本问题。在一个项目中它是 System.Buffers,在另一个项目中它是 System.Text.Encodings.Web。

我没有收到任何错误消息,因为 VS2019 默认关闭了一些异常,因此它们永远不会出现。我刚刚解决了装配问题,一切都按预期进行。

很抱歉占用了一些人的时间,但我不知道 VS 有这个问题。