我正在尝试使用WebClient将新blob上传到Azure存储计数器,如下所示:
var sas = "[a new generated sas with Read, Write, List & Delete permissions]";
var sData = "This is a test!";
var sEndPoint = "http://myaccount.blob.core.windows.net/mycontainer/MyTest.txt" + sas;
var clt = new WebClient();
var res = await clt.UploadStringTaskAsync(sEndPoint, "PUT", sData);
这给了我一个“(400)错误请求”。错误。我在这里做错了吗?
由于
(顺便说一句,我需要使用REST而不是Client API,因为我在Silverlight项目中)
答案 0 :(得分:5)
您需要为blob类型定义请求标头(x-ms-blob-type
)并将其值设置为BlockBlob
。此外,对于Put
请求,您还需要定义Content-Length
请求标头。我写了一篇关于共享访问签名的博客文章,并使用它(包括REST API和存储客户端库)执行一些blob操作,您可以在这里阅读:http://gauravmantri.com/2013/02/13/revisiting-windows-azure-shared-access-signature/。
这里是关于上传blob的帖子的代码。它使用HttpWebRequest / HttpWebResponse而不是WebClient:
static void UploadBlobWithRestAPISasPermissionOnBlobContainer(string blobContainerSasUri)
{
string blobName = "sample.txt";
string sampleContent = "This is sample text.";
int contentLength = Encoding.UTF8.GetByteCount(sampleContent);
string queryString = (new Uri(blobContainerSasUri)).Query;
string blobContainerUri = blobContainerSasUri.Substring(0, blobContainerSasUri.Length - queryString.Length);
string requestUri = string.Format(CultureInfo.InvariantCulture, "{0}/{1}{2}", blobContainerUri, blobName, queryString);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
request.Method = "PUT";
request.Headers.Add("x-ms-blob-type", "BlockBlob");
request.ContentLength = contentLength;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(Encoding.UTF8.GetBytes(sampleContent), 0, contentLength);
}
using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
{
}
}
答案 1 :(得分:1)
在针对blob模拟器进行测试时,这是我需要的代码:
var connection = ConfigurationManager.AppSettings["AzureStorageConnectionString"];
var storageAccount = CloudStorageAccount.Parse(connection);
var client = new WebClient();
client.Headers.Add("x-ms-blob-type", "BlockBlob");
client.Headers.Add("x-ms-version", "2012-02-12");
client.UploadData(string.Format(@"{0}/$root/{1}{2}", storageAccount.BlobEndpoint, myFileName, sharedAccessSignature), "PUT", _content);