我正在尝试使用C#和REST API(在Xamarin.Android中)创建Blob容器。我能够将blob上传到现有容器,但我似乎无法通过REST创建容器。错误是(403)服务器无法验证请求。确保正确形成Authorization标头的值,包括签名。创建授权标头在上传blob时有效,因此它必须与我正在构建要签名的容器字符串的方式相同,但对于我的生活我找不到问题。这是代码:
private async Task<bool> CreateContainer(string containerName)
{
String requestMethod = "PUT";
String msVersion = "2009-09-19";
string dt = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
String canonicalizedHeaders = String.Format("x-ms-date:{0}\nx-ms-version:{1}", dt, msVersion);
String canonicalizedResource = String.Format("/{0}/{1}\nrestype:container", AzureStorageConstants.Account, containerName);
String stringToSign = String.Format("{0}\n\n\n\n\n\n\n\n\n\n\n\n{1}\n{2}", requestMethod, canonicalizedHeaders, canonicalizedResource);
string auth = SignThis(stringToSign);
string urlPath = string.Format("https://{0}.blob.core.windows.net/{1}?restype=container", AzureStorageConstants.Account, containerName);
Uri uri = new Uri(urlPath);
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("x-ms-date", dt);
client.DefaultRequestHeaders.Add("x-ms-version", "2009-09-19");
client.DefaultRequestHeaders.Add("Authorization", auth);
HttpContent empty = null;
HttpResponseMessage response = await client.PutAsync(uri, empty);
return response.IsSuccessStatusCode;
}
private static String SignThis(String StringToSign)
{
String signature = string.Empty;
byte[] unicodeKey = Convert.FromBase64String(AzureStorageConstants.Key);
using (HMACSHA256 hmacSha256 = new HMACSHA256(unicodeKey))
{
Byte[] dataToHmac = System.Text.Encoding.UTF8.GetBytes(StringToSign);
signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
}
String authorizationHeader = String.Format(
CultureInfo.InvariantCulture,
"{0} {1}:{2}",
"SharedKey",
AzureStorageConstants.Account,
signature);
return authorizationHeader;
}
答案 0 :(得分:5)
您的请求失败的原因是您在stringToSign
中未包含内容长度,即使它已包含在请求中(HttpClient包含它并将其值设置为0
})。这导致签名不匹配。要解决此问题,请在stringToSign
中添加内容长度:
String stringToSign = String.Format("{0}\n\n\n0\n\n\n\n\n\n\n\n\n{1}\n{2}", requestMethod, canonicalizedHeaders, canonicalizedResource);