Azure Storage Rest API Demo
本文主要介绍如何使用C#基于Rest API 操作中国版Microsoft Azure Storage,涉及方法Put Blob、Get Blob以及Delete Blob,其它方法参考上面三种方法适当修改即可实现。
相关参考
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的更多相关文章
- 直传文件到Azure Storage的Blob服务中
(此文章同时发表在本人微信公众号“dotNET每日精华文章”,欢迎右边二维码来关注.) 题记:为了庆祝获得微信公众号赞赏功能,忙里抽闲分享一下最近工作的一点心得:如何直接从浏览器中上传文件到Azure ...
- .Net Core Web Api 上传女朋友的照片到微软云Azure Storage
前言 实现一个Web Api,把女朋友照片保存到Azure云的storage里. Image Upload Api 在对应的Api Controller里,加上attribute: [Consumes ...
- Windows Azure Storage (20) 使用Azure File实现共享文件夹
<Windows Azure Platform 系列文章目录> Update 2016-4-14.在Azure VM配置FTP和IIS,请参考: http://blogs.iis.net/ ...
- Windows Azure Cloud Service (12) PaaS之Web Role, Worker Role, Azure Storage Queue(下)
<Windows Azure Platform 系列文章目录> 本章DEMO部分源代码,请在这里下载. 在上一章中,笔者介绍了我们可以使用Azure PaaS的Web Role和Worke ...
- 关于Azure Storage Blob Content-Disposition 使用学习
概述 在常规的HTTP应答中,Content-Disposition 消息头指示回复的内容该以何种形式展示,是以内联的形式(即网页或者页面的一部分),还是以附件的形式下载并保存到本地.通俗的解释就是对 ...
- Azure File Storage 基本用法 -- Azure Storage 之 File
Azure Storage 是微软 Azure 云提供的云端存储解决方案,当前支持的存储类型有 Blob.Queue.File 和 Table. 笔者在<Azure Blob Storage 基 ...
- [New Portal]Windows Azure Storage (14) 使用Azure Blob的PutBlock方法,实现文件的分块、离线上传
<Windows Azure Platform 系列文章目录> 相关内容 Windows Azure Platform (二十二) Windows Azure Storage Servic ...
- Azure Storage Client Library 重试策略建议
有关如何配置 Azure Storage Library 重试策略的信息,可参阅 Gaurav Mantri 撰写的一篇不错的文章<SCL 2.0 – 实施重试策略>.但很难找到关于使用何 ...
- Microsoft Azure Storage Exployer使用指南
概述 Microsoft Azure Storage Exployer 是微软官方推荐的一款管理Azure Storage 客户端工具,客户使用完全免费.支持Windows.Mac和Linux.用户使 ...
随机推荐
- koa2 use里面的next到底是什么
koa2短小精悍,女人不爱男人爱. 之前一只有用koa写一点小程序,自认为还吼吼哈,知道有一天某人问我,你说一下 koa或者express中间件的实现原理.然后我就支支吾吾,好久吃饭都不香. 那么了解 ...
- Java虚拟机--垃圾收集
Java虚拟机 1. JVM运行时数据区域 参考书籍:<深入理解Java虚拟机:JVM高级特性与最佳实践,第二版> 资料参考:http://blog.csdn.net/nms312/art ...
- win7 远程桌面连接过程
背景:在公司日常工作中经常需要是用到远程桌面的连接,在内网环境下,远程桌面连接比qq更加方便!可以考虑外网的连接. 1 准备工作 这里我实验的另一台机器的ip:168.33.51.198,本机ip:1 ...
- springboot用thymeleaf模板的paginate分页
本文根据一个简单的user表为例,展示 springboot集成mybatis,再到前端分页完整代码(新手自学,不足之处欢迎纠正): 先看java部分 pom.xml 加入 <!--支持 Web ...
- Java基础之TCP与UDP
OSI 7层参考模型 物理层 --> 数据链路层 --> 网络层 --> 传输层 --> 会话层 --> 表示层 --> 应用层 按此顺序称为拆包,反之为封包. T ...
- C#去掉JSON字符串中的最后一个数字
这个问题总结起来就是去掉字符串中的最后一个"," 字符串:string s = "1,2,3,4,5," 目标:删除最后一个 "," 方法: ...
- swift3.0 对UITextField()输入框输入的内容进行监控
首先需要继承 UITextFieldDelegate class TestViewController: UIViewController,UITextFieldDelegate{ } 添加事件委托 ...
- java集合框架的讲解
下面要开始java中相关集合框架的学习啦. Are you ready?Let's go~~ 今天要讲解的Java中的集合框架. 1) 首先查看jdk中Collection类的源码后会发现如下内容: ...
- android.intent.action.MAIN与android.intent.category.LAUNCHER
android.intent.action.MAIN 决定应用程序最先启动的Activity android.intent.category.LAUNCHER 决定应用程序是否显示在程序列表里 在网上 ...
- 【性能测试工具】-SIEGE、HTTP_LOAD、WebBench、Apache-ab
//当使用其它的开源测试工具的时候,也可以参考这一点:进入到bin目录 //如果工具本身不包含bin文件,那么在工具的1级目录执行即可 (1) SIEGE $cd /home/userNa ...