本文主要介绍如何使用C#基于Rest API 操作中国版Microsoft Azure Storage,涉及方法Put Blob、Get Blob以及Delete Blob,其它方法参考上面三种方法适当修改即可实现。

相关参考

GitHub参考链接

Operations on Blobs

更多Azure Storage C#开发Demo

C# Code Demo

注意:基本连接信息需要修改为用户个人账户信息

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;
}
}
}
}

Azure Storage Rest API Demo的更多相关文章

  1. 直传文件到Azure Storage的Blob服务中

    (此文章同时发表在本人微信公众号“dotNET每日精华文章”,欢迎右边二维码来关注.) 题记:为了庆祝获得微信公众号赞赏功能,忙里抽闲分享一下最近工作的一点心得:如何直接从浏览器中上传文件到Azure ...

  2. .Net Core Web Api 上传女朋友的照片到微软云Azure Storage

    前言 实现一个Web Api,把女朋友照片保存到Azure云的storage里. Image Upload Api 在对应的Api Controller里,加上attribute: [Consumes ...

  3. Windows Azure Storage (20) 使用Azure File实现共享文件夹

    <Windows Azure Platform 系列文章目录> Update 2016-4-14.在Azure VM配置FTP和IIS,请参考: http://blogs.iis.net/ ...

  4. Windows Azure Cloud Service (12) PaaS之Web Role, Worker Role, Azure Storage Queue(下)

    <Windows Azure Platform 系列文章目录> 本章DEMO部分源代码,请在这里下载. 在上一章中,笔者介绍了我们可以使用Azure PaaS的Web Role和Worke ...

  5. 关于Azure Storage Blob Content-Disposition 使用学习

    概述 在常规的HTTP应答中,Content-Disposition 消息头指示回复的内容该以何种形式展示,是以内联的形式(即网页或者页面的一部分),还是以附件的形式下载并保存到本地.通俗的解释就是对 ...

  6. Azure File Storage 基本用法 -- Azure Storage 之 File

    Azure Storage 是微软 Azure 云提供的云端存储解决方案,当前支持的存储类型有 Blob.Queue.File 和 Table. 笔者在<Azure Blob Storage 基 ...

  7. [New Portal]Windows Azure Storage (14) 使用Azure Blob的PutBlock方法,实现文件的分块、离线上传

    <Windows Azure Platform 系列文章目录> 相关内容 Windows Azure Platform (二十二) Windows Azure Storage Servic ...

  8. Azure Storage Client Library 重试策略建议

    有关如何配置 Azure Storage Library 重试策略的信息,可参阅 Gaurav Mantri 撰写的一篇不错的文章<SCL 2.0 – 实施重试策略>.但很难找到关于使用何 ...

  9. Microsoft Azure Storage Exployer使用指南

    概述 Microsoft Azure Storage Exployer 是微软官方推荐的一款管理Azure Storage 客户端工具,客户使用完全免费.支持Windows.Mac和Linux.用户使 ...

随机推荐

  1. A----奇怪的玩意

      题目: 我们的化学生物学家发明了一种新的叫stripies非常神奇的生命.该stripies是透明的无定形变形虫似的生物,生活在果冻状的营养培养基平板菌落.大部分的时间stripies在移动.当他 ...

  2. FreeRTOS——中断管理

    1. 只有以“FromISR”或"FROM_ISR"结束的API函数或宏才可以在中断服务函数中使用. 2. 除互斥信号量外,所有类型的信号量都可以调用 xSemaphoreTake ...

  3. hdu_5964:平行四边形

    打重现赛时,一点思路也没有,然后又看到这题AC数那么少,就直接放弃了.今天重新看了看,借鉴了下别人的,发现此题应该算是一道可解题. 看上去,这题的ans是同时有两个点作为自变量的函数(然而n^2复杂度 ...

  4. 控制反转(IoC)-解析与实现

    控制反转(Inversion of Control)缩写:IoC是面向对象编程中框架级别里的一个重要的概念, 可以说Spring框架的核心就是基于IoC原理的. 这个概念到底是什么呢? 这么讲吧,一个 ...

  5. HBase(0.96以上版本)过滤器Filter详解及实例代码

    说明: 本文参考官方Ref Guide,Developer API和众多博客,并结合实测代码编写,详细总结HBase的Filter功能,并附上每类Filter的相应代码实现. 本文尽量遵从Ref Gu ...

  6. Java中使用POI读取大的Excel文件或者输入流时发生out of memory异常参考解决方案

    注意:此参考解决方案只是针对xlsx格式的excel文件! 背景 前一段时间遇到一种情况,服务器经常宕机,而且没有规律性,查看GC日志发生了out of memory,是堆溢出导致的,分析了一下堆的d ...

  7. C#多线程之旅(7)——终止线程

    先交代下背景,写<C#多线程之旅>这个系列文章主要是因为以下几个原因:1.多线程在C/S和B/S架构中用得是非常多的;2.而且多线程的使用是非常复杂的,如果没有用好,容易造成很多问题.   ...

  8. [技术] OIer的STL入门教程

    注: 本文主要摘取STL在OI中的常用技巧应用, 所以可能会重点说明容器部分和算法部分, 且不会讨论所有支持的函数/操作并主要讨论 C++11 前支持的特性. 如果需要详细完整的介绍请自行查阅标准文档 ...

  9. python 密码学编程 -- 2

    接上一篇随笔 ******************************************************************** * quote : "http://i ...

  10. Hibernate 中Criteria Query查询详解【转】

    当查询数据时,人们往往需要设置查询条件.在SQL或HQL语句中,查询条件常常放在where子句中.此外,Hibernate还支持Criteria查询(Criteria Query),这种查询方式把查询 ...