HTTP 400:附加到 Azure blob 时请求错误

HTTP 400: Bad Request when appending to Azure blob

我在尝试将字节追加到 Azure 存储中的追加 blob 时收到 HTTP 400 错误请求。 Azure 存储帐户已存在。

A​​zure 文档只有一个调用 AppendText() 方法的示例,但此方法包含有关将此方法用于多个客户端编写器的警告。因此,我想改用 AppendBlock() 方法,以确保调用是原子的。

var cred = new StorageCredentials("storageaccountname", "storageaccountkey");
var account = new CloudStorageAccount(cred, true);

var client = account.CreateCloudBlobClient();
var container = client.GetContainerReference("csharp");
container.CreateIfNotExists();

var log = container.GetAppendBlobReference("artofshell.log");
var stream = new MemoryStream(1024);
var text = System.Text.Encoding.ASCII.GetBytes("Log entry #1");
stream.Write(text, 0, text.Length);

log.CreateOrReplace();
log.AppendBlock(stream);

知道是什么原因造成的吗?

要解决此问题,请在调用 AppendBlock() 之前重置流的位置。所以你的代码将是:

        log.CreateOrReplace();
        stream.Position = 0;//Reset stream's position
        log.AppendBlock(stream);

您收到此错误的原因是您试图发送 0 字节。因为流位于末尾,所以您尝试发送的内容的长度是 0 并且存储服务不喜欢它:)。当我 运行 你的代码并在 Fiddler 中跟踪 request/response 时,我得到了 400 错误以及以下详细信息:

<?xml version="1.0" encoding="utf-8"?>
    <Error>
        <Code>InvalidHeaderValue</Code>
        <Message>
            The value for one of the HTTP headers is not in the correct format.
            RequestId:b265553a-0001-0072-6e58-ae8e34000000
            Time:2016-05-15T03:15:51.0349150Z
        </Message>
        <HeaderName>
            Content-Length
        </HeaderName>
        <HeaderValue>
            0
        </HeaderValue>
    </Error>