设为首页 收藏本站
查看: 843|回复: 0

[经验分享] Azure Storage Rest API Demo

[复制链接]

尚未签到

发表于 2017-6-30 07:14:23 | 显示全部楼层 |阅读模式
using System;  using System.Collections;
  using System.Collections.Specialized;
  using System.Globalization;
  using System.IO;
  using System.Net;
  using System.Text;
  using System.Web;
  namespace StorageRestApi
  {
  class Program
  {
  static void Main(string[] args)
  {
  string uri = string.Concat("http://", AzureConstants.Account, ".blob.core.chinacloudapi.cn/");//注意正确修改指向中国版Azure的终结点
  BlobHelper helper = new BlobHelper("BlockBlob", uri);
  var conteudo = File.ReadAllBytes(@"D:\test.jpg");//本地存储文件的位置
  helper.PutBlob("test", "imagens2k13", conteudo); //put blob
  Console.WriteLine("Put blob success!");
  byte[] retorno = null;
  retorno = helper.GetBlob("test", "imagens2k13"); //get blob
  Console.WriteLine("Get blob success!");
  helper.DeleteBlob("test", "imagens2k13"); //delete blob
  Console.WriteLine("Delete blob success!");
  Console.Read();
  }
  }
  //存储信息初始化配置 基本配置
  class AzureConstants
  {
  //存储账户
  public static string Account = "<storage account name>";
  //存储密码
  public static string SecretKey = "<storage account key>";
  public static string SharedKeyAuthorizationScheme = "SharedKey";
  }
  class BlobHelper
  {
  public BlobHelper(string blobType, string blobEndPoint)
  {
  BlobType = blobType;
  BlobEndPoint = blobEndPoint;
  }
  public string BlobType { get; set; }
  public string BlobEndPoint { get; set; }
  private string CreateAuthorizationHeader(string canonicalizedstring)
  {
  string signature = string.Empty;
  using (
  System.Security.Cryptography.HMACSHA256 hmacSha256 =
  new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(AzureConstants.SecretKey)))
  {
  Byte[] dataToHmac = System.Text.Encoding.UTF8.GetBytes(canonicalizedstring);
  signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
  }
  string authorizationHeader = string.Format(CultureInfo.InvariantCulture, "{0} {1}:{2}",
  AzureConstants.SharedKeyAuthorizationScheme,
  AzureConstants.Account, signature);
  return authorizationHeader;
  }
  public string AuthorizationHeader(string method, DateTime now, HttpWebRequest request, string ifMatch = "", string md5 = "")
  {
  string MessageSignature;
  MessageSignature = String.Format("{0}\n\n\n{1}\n{5}\n\n\n\n{2}\n\n\n\n{3}{4}",
  method,
  (method == "GET" || method == "HEAD") ? String.Empty : request.ContentLength.ToString(),
  ifMatch,
  GetCanonicalizedHeaders(request),
  GetCanonicalizedResource(request.RequestUri, AzureConstants.Account),
  md5
  );
  byte[] SignatureBytes = System.Text.Encoding.UTF8.GetBytes(MessageSignature);
  System.Security.Cryptography.HMACSHA256 SHA256 = new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(AzureConstants.SecretKey));
  String AuthorizationHeader = "SharedKey " + AzureConstants.Account + ":" + Convert.ToBase64String(SHA256.ComputeHash(SignatureBytes));
  return AuthorizationHeader;
  }
  public string GetCanonicalizedResource(Uri address, string accountName)
  {
  StringBuilder str = new StringBuilder();
  StringBuilder builder = new StringBuilder("/");
  builder.Append(accountName);
  builder.Append(address.AbsolutePath);
  str.Append(builder.ToString());
  NameValueCollection values2 = new NameValueCollection();
  NameValueCollection values = HttpUtility.ParseQueryString(address.Query);
  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 > 0)
  {
  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.Append("\n");
  str.Append(builder3.ToString());
  }
  return str.ToString();
  }
  public string GetCanonicalizedHeaders(HttpWebRequest request)
  {
  ArrayList headerNameList = new ArrayList();
  StringBuilder sb = new StringBuilder();
  foreach (string headerName in request.Headers.Keys)
  {
  if (headerName.ToLowerInvariant().StartsWith("x-ms-", StringComparison.Ordinal))
  {
  headerNameList.Add(headerName.ToLowerInvariant());
  }
  }
  headerNameList.Sort();
  foreach (string headerName in headerNameList)
  {
  StringBuilder builder = new StringBuilder(headerName);
  string separator = ":";
  foreach (string headerValue in GetHeaderValues(request.Headers, headerName))
  {
  string trimmedValue = headerValue.Replace("\r\n", String.Empty);
  builder.Append(separator);
  builder.Append(trimmedValue);
  separator = ",";
  }
  sb.Append(builder.ToString());
  sb.Append("\n");
  }
  return sb.ToString();
  }
  public 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(null));
  }
  }
  return list;
  }
  public async void PutBlob(String containerName, String blobName, byte[] blobContent, bool error = false)
  {
  String requestMethod = "PUT";
  String urlPath = String.Format("{0}/{1}", containerName, blobName);
  String storageServiceVersion = "2009-09-19";
  String dateInRfc1123Format = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
  Int32 blobLength = blobContent.Length;
  String canonicalizedHeaders = String.Format(
  "x-ms-blob-type:{0}\nx-ms-date:{1}\nx-ms-version:{2}",
  BlobType,
  dateInRfc1123Format,
  storageServiceVersion);
  String canonicalizedResource = String.Format("/{0}/{1}", AzureConstants.Account, urlPath);
  String stringToSign = String.Format(
  "{0}\n\n\n{1}\n\n\n\n\n\n\n\n\n{2}\n{3}",
  requestMethod,
  blobLength,
  canonicalizedHeaders,
  canonicalizedResource);
  String authorizationHeader = CreateAuthorizationHeader(stringToSign);
  Uri uri = new Uri(BlobEndPoint + urlPath);
  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
  request.Method = requestMethod;
  request.Headers["x-ms-blob-type"] = BlobType;
  request.Headers["x-ms-date"] = dateInRfc1123Format;
  request.Headers["x-ms-version"] = storageServiceVersion;
  request.Headers["Authorization"] = authorizationHeader;
  request.ContentLength = blobLength;
  try
  {
  using (Stream requestStream = await request.GetRequestStreamAsync())
  {
  requestStream.Write(blobContent, 0, blobLength);
  }
  using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
  {
  String ETag = response.Headers["ETag"];
  System.Diagnostics.Debug.WriteLine(ETag);
  }
  error = false;
  }
  catch (WebException ex)
  {
  System.Diagnostics.Debug.WriteLine("An error occured. Status code:" + ((HttpWebResponse)ex.Response).StatusCode);
  System.Diagnostics.Debug.WriteLine("Error information:");
  error = true;
  using (Stream stream = ex.Response.GetResponseStream())
  {
  using (StreamReader sr = new StreamReader(stream))
  {
  var s = sr.ReadToEnd();
  System.Diagnostics.Debug.WriteLine(s);
  }
  }
  }
  }
  public byte[] GetBlob(String containerName, String blobName)
  {
  String urlPath = String.Format("{0}/{1}", containerName, blobName);
  DateTime now = DateTime.UtcNow;
  string uri = BlobEndPoint + urlPath;
  HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest;
  request.Method = "GET";
  request.ContentLength = 0;
  request.Headers.Add("x-ms-date", now.ToString("R", System.Globalization.CultureInfo.InvariantCulture));
  request.Headers.Add("x-ms-version", "2009-09-19");
  request.Headers.Add("Authorization", AuthorizationHeader("GET", now, request, "", ""));
  var bytes = default(byte[]);
  using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
  {
  String ETag = response.Headers["ETag"];
  System.Diagnostics.Debug.WriteLine(ETag);
  using (Stream stream = response.GetResponseStream())
  {
  using (StreamReader sr = new StreamReader(stream))
  {
  using (var memstream = new MemoryStream())
  {
  sr.BaseStream.CopyTo(memstream);
  bytes = memstream.ToArray();
  }
  }
  }
  }
  return bytes;
  }
  public bool DeleteBlob(String containerName, String blobName)
  {
  String requestMethod = "DELETE";
  String urlPath = String.Format("{0}/{1}", containerName, blobName);
  String storageServiceVersion = "2009-09-19";
  String dateInRfc1123Format = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
  Int32 blobLength = 0; // blobContent.Length;
  String canonicalizedHeaders = String.Format(
  "x-ms-blob-type:{0}\nx-ms-date:{1}\nx-ms-version:{2}",
  BlobType,
  dateInRfc1123Format,
  storageServiceVersion);
  String canonicalizedResource = String.Format("/{0}/{1}", AzureConstants.Account, urlPath);
  String stringToSign = String.Format(
  "{0}\n\n\n{1}\n\n\n\n\n\n\n\n\n{2}\n{3}",
  requestMethod,
  blobLength,
  canonicalizedHeaders,
  canonicalizedResource);
  String authorizationHeader = CreateAuthorizationHeader(stringToSign);
  Uri uri = new Uri(BlobEndPoint + urlPath);
  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
  request.Method = requestMethod;
  request.Headers["x-ms-blob-type"] = BlobType;
  request.Headers["x-ms-date"] = dateInRfc1123Format;
  request.Headers["x-ms-version"] = storageServiceVersion;
  request.Headers["Authorization"] = authorizationHeader;
  request.ContentLength = blobLength;
  try
  {
  using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
  {
  String ETag = response.Headers["ETag"];
  System.Diagnostics.Debug.WriteLine(ETag);
  return true;
  }
  }
  catch (WebException ex)
  {
  System.Diagnostics.Debug.WriteLine("An error occured. Status code:" + ((HttpWebResponse)ex.Response).StatusCode);
  System.Diagnostics.Debug.WriteLine("Error information:");
  return false;
  }
  }
  }
  }

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-389535-1-1.html 上篇帖子: C# Azure 存储-队列 下篇帖子: Microsoft Azure IoTHub Serials 1
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表