本文主要介绍如何使用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. Maven在导入其他项目时报错:Plugin execution not covered by lifecycle configuration

    这几天想把Spring 攻略第二版完整的学习下,所以就在网上下载了该教材的源码,寻思边看书边练习!之前有过一些Maven开发的相关经验,觉得Maven在引入jar包上的配置还是很方便的,所以这次源码的 ...

  2. (转)Java线程:新特征-线程池

    Java线程:新特征-线程池   Sun在Java5中,对Java线程的类库做了大量的扩展,其中线程池就是Java5的新特征之一,除了线程池之外,还有很多多线程相关的内容,为多线程的编程带来了极大便利 ...

  3. JVM常用启动参数

    本文参考 jvm参数设置大全:http://www.cnblogs.com/marcotan/p/4256885.html 堆内存分配及gc:http://www.cnblogs.com/weiguo ...

  4. 【css】border-image

    1. border-image 一个新css3 样式 给边框增加图片,还可以拉升 或重复图片 round 为重复 sketch 为拉升 border: 15px solid transparent; ...

  5. NSScanner扫描字符串中()的内容

    //本事例去除小括号及其内部的内容 + (NSString *)changeStringWithString:(NSString *)string {  NSScanner*scanner = [NS ...

  6. [补档]暑假集训D5总结

    %dalao 今天又有dalao来讲课,讲的是网络流 网络流--从入门到放弃:7-29dalao讲课笔记--https://hzoi-mafia.github.io/2017/07/29/27/   ...

  7. 机器学习实战 logistic回归 python代码

    # -*- coding: utf-8 -*- """ Created on Sun Aug 06 15:57:18 2017 @author: mdz "&q ...

  8. mbos之动态图表设计

    前言 所谓,一图胜千言.人脑有80%的部分专门用于视觉处理.而随着数据时代的全面来临,我们自然有必要将数据转化为图形与图表. Mbos是一个快速,稳定的云端轻应用开发平台.帮助企业快速开发移动应用,加 ...

  9. sql 日记

    --4.选择雇用时间在1998-02-01到1998-05-01之间的员工姓名,job_id和雇用时间select last_name,job_id,hire_datefrom employeeswh ...

  10. oracle 内连接,外连接

    --内连接  inner join  ...  on  --左外连接 left join ... on  --右外连接  right join ... on 列: select * from stud ...