ASP.NET Core 2.0中的Azure Blob存储
问题
如何在ASP.NET Core中使用Azure Blob存储
解
创建一个类库并添加NuGet包 - WindowsAzure.Storage
添加一个类来封装设置,
publicclass AzureBlobSetings
{
public AzureBlobSetings(string storageAccount,
string storageKey,
string containerName)
{
if (string.IsNullOrEmpty(storageAccount))
thrownew ArgumentNullException("StorageAccount");
if (string.IsNullOrEmpty(storageKey))
thrownew ArgumentNullException("StorageKey");
if (string.IsNullOrEmpty(containerName))
thrownew ArgumentNullException("ContainerName");
this.StorageAccount = storageAccount;
this.StorageKey = storageKey;
this.ContainerName = containerName;
}
public string StorageAccount { get; }
public string StorageKey { get; }
public string ContainerName { get; }
}
添加一个类来封装一个blob项目,
publicclass AzureBlobItem
{
public AzureBlobItem(IListBlobItem item)
{
this.Item = item;
}
public IListBlobItem Item { get; }
public bool IsBlockBlob => Item.GetType() == typeof(CloudBlockBlob);
public bool IsPageBlob => Item.GetType() == typeof(CloudPageBlob);
public bool IsDirectory => Item.GetType() == typeof(CloudBlobDirectory);
public string BlobName => IsBlockBlob ? ((CloudBlockBlob)Item).Name :
IsPageBlob ? ((CloudPageBlob)Item).Name :
IsDirectory ? ((CloudBlobDirectory)Item).Prefix :
"";
public string Folder => BlobName.Contains("/") ?
BlobName.Substring(0, BlobName.LastIndexOf("/")) : "";
public string Name => BlobName.Contains("/") ?
BlobName.Substring(BlobName.LastIndexOf("/") + 1) : BlobName;
}
Add a class to encapsulate storage access. Add a private helper methods to access storage,
private async Task<CloudBlobContainer> GetContainerAsync()
{
//Account
CloudStorageAccount storageAccount = new CloudStorageAccount(
new StorageCredentials(settings.StorageAccount, settings.StorageKey), false);
//Client
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
//Container
CloudBlobContainer blobContainer =
blobClient.GetContainerReference(settings.ContainerName);
await blobContainer.CreateIfNotExistsAsync();
return blobContainer;
}
private async Task<CloudBlockBlob> GetBlockBlobAsync(string blobName)
{
//Container
CloudBlobContainer blobContainer = await GetContainerAsync();
//Blob
CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(blobName);
return blockBlob;
}
private async Task<List<AzureBlobItem>> GetBlobListAsync(
bool useFlatListing = true)
{
//Container
CloudBlobContainer blobContainer = await GetContainerAsync();
//List
var list = new List<AzureBlobItem>();
BlobContinuationToken token = null;
do
{
BlobResultSegment resultSegment =
await blobContainer.ListBlobsSegmentedAsync("", useFlatListing,
new BlobListingDetails(), null, token, null, null);
token = resultSegment.ContinuationToken;
foreach (IListBlobItem item in resultSegment.Results)
{
list.Add(new AzureBlobItem(item));
}
} while (token != null);
return list.OrderBy(i => i.Folder).ThenBy(i => i.Name).ToList();
}
现在添加公共方法来上传和下载blob项目,
public async Task UploadAsync(string blobName, string filePath)
{
//Blob
CloudBlockBlob blockBlob = await GetBlockBlobAsync(blobName);
//Upload
using (var fileStream = System.IO.File.Open(filePath, FileMode.Open))
{
fileStream.Position = 0;
await blockBlob.UploadFromStreamAsync(fileStream);
}
}
public async Task UploadAsync(string blobName, Stream stream)
{
//Blob
CloudBlockBlob blockBlob = await GetBlockBlobAsync(blobName);
//Upload
stream.Position = 0;
await blockBlob.UploadFromStreamAsync(stream);
}
public async Task<MemoryStream> DownloadAsync(string blobName)
{
//Blob
CloudBlockBlob blockBlob = await GetBlockBlobAsync(blobName);
//Download
using (var stream = new MemoryStream())
{
await blockBlob.DownloadToStreamAsync(stream);
return stream;
}
}
public async Task DownloadAsync(string blobName, string path)
{
//Blob
CloudBlockBlob blockBlob = await GetBlockBlobAsync(blobName);
//Download
await blockBlob.DownloadToFileAsync(path, FileMode.Create);
}
添加方法来获取blob项目列表,
public async Task<List<AzureBlobItem>> ListAsync()
{
return await GetBlobListAsync();
}
public async Task<List<string>> ListFoldersAsync()
{
var list = await GetBlobListAsync();
return list.Where(i => !string.IsNullOrEmpty(i.Folder))
.Select(i => i.Folder)
.Distinct()
.OrderBy(i => i)
.ToList();
}
注入和使用存储助手,
publicclass HomeController : Controller
{
private readonly IAzureBlobStorage blobStorage;
public HomeController(IAzureBlobStorage blobStorage)
{
this.blobStorage = blobStorage;
}
注意
示例代码具有一个控制器,其中包含列出,下载和上载项目的操作。
在 ASP.NET核心 Web应用程序中,配置服务,
publicvoid ConfigureServices(
IServiceCollection services)
{
services.AddScoped<IAzureBlobStorage>(factory =>
{
returnnew AzureBlobStorage(new AzureBlobSetings(
storageAccount: Configuration["Blob_StorageAccount"],
storageKey: Configuration["Blob_StorageKey"],
containerName: Configuration["Blob_ContainerName"]));
});
services.AddMvc();
}
讨论
示例代码将要求您设置Azure帐户,Blob存储帐户和容器。这些指令可以在这里找到
ASP.NET Core 2.0中的Azure Blob存储的更多相关文章
- 在ASP.NET Core 1.0中如何发送邮件
(此文章同时发表在本人微信公众号"dotNET每日精华文章",欢迎右边二维码来关注.) 题记:目前.NET Core 1.0中并没有提供SMTP相关的类库,那么要如何从ASP.NE ...
- ASP.NET Core 1.0 中的依赖项管理
var appInsights=window.appInsights||function(config){ function r(config){t[config]=function(){var i= ...
- ASP.NET Core 1.0 中使用 Swagger 生成文档
github:https://github.com/domaindrivendev/Ahoy 之前文章有介绍在ASP.NET WebAPI 中使用Swagger生成文档,ASP.NET Core 1. ...
- 用ASP.NET Core 1.0中实现邮件发送功能
准备将一些项目迁移到 asp.net core 先从封装类库入手,在遇到邮件发送类时发现在 asp.net core 1.0中并示提供SMTP相关类库,于是网上一搜发现了MailKit 好东西一定要试 ...
- 在ASP.NET Core 2.0中使用CookieAuthentication
在ASP.NET Core中关于Security有两个容易混淆的概念一个是Authentication(认证),一个是Authorization(授权).而前者是确定用户是谁的过程,后者是围绕着他们允 ...
- 如何在ASP.NET Core 2.0中使用Razor页面
如何在ASP.NET Core 2.0中使用Razor页面 DotNetCore2017-11-22 14:49 问题 如何在ASP.NET Core 2.0中使用Razor页面 解 创建一个空的项 ...
- ASP.NET Core 3.0中使用动态控制器路由
原文:Dynamic controller routing in ASP.NET Core 3.0 作者:Filip W 译文:https://www.cnblogs.com/lwqlun/p/114 ...
- asp.net core 3.0 中使用 swagger
asp.net core 3.0 中使用 swagger Intro 上次更新了 asp.net core 3.0 简单的记录了一下 swagger 的使用,那个项目的 api 比较简单,都是匿名接口 ...
- 探索 ASP.Net Core 3.0系列三:ASP.Net Core 3.0中的Service provider validation
前言:在本文中,我将描述ASP.NET Core 3.0中新的“validate on build”功能. 这可以用来检测您的DI service provider是否配置错误. 具体而言,该功能可检 ...
随机推荐
- dwz监听日期变化,dwz日期控件onchange不起作用,dwz框架时间控件不支持onchange事件
转载自:http://blog.csdn.net/sp308036654/article/details/50638348 <input type="text" class= ...
- Linux之RPM GPG签名
原文地址:http://linux.chinaunix.net/techdoc/system/2007/09/26/968723.shtml GPG在Linux上的应用主要是实现官方发布的包的签名机制 ...
- nignx重启
.进入nginx安装目录sbin下 .输入./nginx -s reload
- mysql索引原理及用法
MySQL索引原理及慢查询优化 Mysql explain用法和性能分析 MySQL 索引优化全攻略 1.索引作用 在索引列上,除了上面提到的有序查找之外,数据库利用各种各样的快速定位技术,能够大大提 ...
- Some details of UIKit
[Some details of UIKit] 1.UIViewController的toolbarItems属性与UINavigationController配合使用. 2.The view for ...
- ZOJ2388 Beat the Spread! 2017-04-16 19:18 91人阅读 评论(0) 收藏
Beat the Spread! Time Limit: 2 Seconds Memory Limit: 65536 KB Superbowl Sunday is nearly here. ...
- 别做HR最讨厌的求职者
有些求职者认为自己各方面都与所应聘的职位要求相匹配,因此在被淘汰之后总是特别不解,努力回忆起每个面试环节,却始终找不到原因.是的,也许你真的很优秀,但是你被淘汰了,原因也许并不大,只是你得罪了HR.其 ...
- 初尝2D骨骼动画编辑工具SPINE,并into Unity3D
一.SPINE使用 研究2D骨骼动画,CYou的朋友介绍我SPINE这个工具,开发自Esoteric Software的一款专门制作2D动画的软件,网络上的资料还很少,我这从半吊子美术技术的角度简单说 ...
- 两种步骤 更改 EBS R12界面LOGO以及内容
from:metalink more: Note 174219.1 - How To Change The Logo In The Oracle Application Menu Note 84975 ...
- Github注册及心得
注册Github流程: 1.搜索www.github.com 2.有两个按钮sign up(注册).sign in(登入)