Azure REST API (2) Azure Storage

时间:2023-03-09 02:21:59
Azure REST API (2) Azure Storage

  《Windows Azure Platform 系列文章目录

  注意:本文适用于国内由世纪互联运维的Azure China。

  本文将会介绍如何使用REST API来直接访问Storage Service。

  项目文件在这里下载

  1.首先我们以管理员身份,创建一个Windows Console项目

  2.在Program.cs中,增加如下代码

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web; namespace AzureStorageRestAPI
{
class Program
{ internal class CanonicalizedString
{ private StringBuilder canonicalizedString = new StringBuilder(); internal CanonicalizedString(string initialElement)
{ this.canonicalizedString.Append(initialElement);
} internal void AppendCanonicalizedElement(string element)
{ this.canonicalizedString.Append("\n");
this.canonicalizedString.Append(element);
} internal string Value
{
get
{
return this.canonicalizedString.ToString(); }
} } const string bloburi = @"https://leidemo.blob.core.chinacloudapi.cn";
const string accountname = "leidemo";
const string key = "EZNbnhPJ7+Fv6X5k9OW36ece5WflDJaUvGjdVpdwxEXsKVzEa18/Rw2f30d6ASELNYE7XlvFs78nfCw+UIs3kQ==";
const string method = "GET"; static void Main(string[] args)
{
string AccountName = accountname;
string AccountSharedKey = key;
string Address = bloburi;
string container = "public"; // 创建请求字符串
string QueryString = "?restype=container&comp=list";
Uri requesturi = new Uri(Address + "/" + container + QueryString);
string MessageSignature = ""; // 创建HttpWebRequest类 HttpWebRequest Request = (HttpWebRequest)HttpWebRequest.Create(requesturi.AbsoluteUri); Request.Method = method; Request.ContentLength = ; Request.Headers.Add("x-ms-date", DateTime.UtcNow.ToString("R")); Request.Headers.Add("x-ms-version", "2009-09-19"); // 开始创建签名 MessageSignature += "GET\n"; // Verb MessageSignature += "\n"; // Content-Encoding MessageSignature += "\n"; // Content-Language MessageSignature += "\n"; // Content-Length MessageSignature += "\n"; // Content-MD5 MessageSignature += "\n"; // Content-Type MessageSignature += "\n"; // Date MessageSignature += "\n"; // If-Modified-Since MessageSignature += "\n"; // If-Match MessageSignature += "\n"; // If-None-Match MessageSignature += "\n"; // If-Unmodified-Since MessageSignature += "\n"; // Range // CanonicalizedHeaders ArrayList list = new ArrayList(); foreach (string str in Request.Headers.Keys)
{ if (str.ToLowerInvariant().StartsWith("x-ms-", StringComparison.Ordinal))
{ list.Add(str.ToLowerInvariant()); } } list.Sort(); foreach (string str2 in list)
{ StringBuilder builder = new StringBuilder(str2); string str3 = ":"; foreach (string str4 in GetHeaderValues(Request.Headers, str2))
{ string str5 = str4.Replace("\r\n", string.Empty); builder.Append(str3); builder.Append(str5); str3 = ","; } MessageSignature += builder.ToString() + "\n"; } MessageSignature += GetCanonicalizedResourceVersion2(requesturi, AccountName); // 开始创建签名 byte[] SignatureBytes = System.Text.Encoding.UTF8.GetBytes(MessageSignature); System.Security.Cryptography.HMACSHA256 SHA256 = new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(AccountSharedKey)); // 创建Authorization HTTP消息头的值 String AuthorizationHeader = "SharedKey " + AccountName + ":" + Convert.ToBase64String(SHA256.ComputeHash(SignatureBytes)); // 把编码后的签名加入到Authorization HTTP消息头中 Request.Headers.Add("Authorization", AuthorizationHeader); // 获取返回消息 using (HttpWebResponse response = (HttpWebResponse)Request.GetResponse())
{ if (response.StatusCode == HttpStatusCode.OK)
{ // 服务器返回成功消息 using (Stream stream = response.GetResponseStream())
{ using (StreamReader sr = new StreamReader(stream))
{ var s = sr.ReadToEnd(); // 输出返回消息 Console.WriteLine(s); } } } else
{ // 这里可以抛出异常信息 } } Console.ReadLine(); } static ArrayList GetHeaderValues(NameValueCollection headers, string headerName)
{ ArrayList list = new ArrayList(); string[] values = headers.GetValues(headerName); if (values != null)
{ foreach (string str in values)
{ list.Add(str.TrimStart(new char[])); } } return list; } static string GetCanonicalizedResourceVersion2(Uri address, string accountName)
{ StringBuilder builder = new StringBuilder("/"); builder.Append(accountName); builder.Append(address.AbsolutePath); CanonicalizedString str = new CanonicalizedString(builder.ToString()); NameValueCollection values = HttpUtility.ParseQueryString(address.Query); NameValueCollection values2 = new NameValueCollection(); foreach (string str2 in values.Keys)
{ ArrayList list = new ArrayList(values.GetValues(str2)); list.Sort(); StringBuilder builder2 = new StringBuilder(); foreach (object obj2 in list)
{ if (builder2.Length > )
{ builder2.Append(","); } builder2.Append(obj2.ToString()); } values2.Add((str2 == null) ? str2 : str2.ToLowerInvariant(), builder2.ToString()); } ArrayList list2 = new ArrayList(values2.AllKeys); list2.Sort(); foreach (string str3 in list2)
{ StringBuilder builder3 = new StringBuilder(string.Empty); builder3.Append(str3); builder3.Append(":"); builder3.Append(values2[str3]); str.AppendCanonicalizedElement(builder3.ToString()); } return str.Value; } }
}

  

  3.在调试项目的时候,注意修改以下参数:

  const string bloburi = @"https://leidemo.blob.core.chinacloudapi.cn";       //修改为Storage Endpoint

  const string accountname = "leidemo";                       //修改为你的存储账号名称

  const string key = "[YourStorageAccountKey]";                   //修改为你的存储账号Key

  string container = "public";                                //修改为存储账号的Container Name

  4.运行成功,你将会看到Console程序输出如下信息,内容为名为存储账号leidemo,Container为public中所有Blob的信息:

  参考资料:http://blogs.msdn.com/b/azchina/archive/2010/03/19/windows-azure-rest-api-storage-service.aspx