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是否配置错误. 具体而言,该功能可检 ...
随机推荐
- php通过反射执行某方法
简单记录下通过反射来获取某方法的参数,然后利用php内置函数类执行此方法 一个简单的test类 class test { //2个参数默认值 public function b($name='lemo ...
- Introduction Sockets to Programming in C using TCP/IP
Introduction Computer Network: hosts, routers, communication channels Hosts run applications Routers ...
- string 转换为枚举对应的值
public static Object Parse(Type enumType,string value) 例如:(Colors)Enum.Parse(typeof(Colors), "R ...
- [label][JavaScript] 自动填充内容的JavaScript 库
一个帮助你针对不同标签自动填入内容的轻量级javascript类库 - fixiejs http://www.gbtags.com/technology/javascript/20120802-fix ...
- 软件项目第一个Sprint评分
第一组 跑男 跑男组他们设计的是极速蜗牛小游戏,他们的界面背景图片做的挺漂亮,现在为止也实现了大部分功能, 但是我没有太听懂他们的游戏规则. 因为蜗牛出发后,每次碰到屏幕边缘后都会有确定的反弹结果,也 ...
- [leetcode] 13. Remove Duplicates from Sorted List
这个题目其实不难的,主要是我C++的水平太差了,链表那里绊了好久,但是又不像用python,所以还是强行上了. 题目如下: Given a sorted linked list, delete all ...
- Sharepoint安装的几处注意事项
0.sharepoint自带组件安装,无需另下载安装 1.必须安装域(不安装会提示sharepoint 指定的用户是本地账户) 2.域安装后需要在sharepoint设置的数据库账号具有域权限及高级权 ...
- Java异常:选择Checked Exception还是Unchecked Exception?
http://blog.csdn.net/kingzone_2008/article/details/8535287 Java包含两种异常:checked异常和unchecked异常.C#只有unch ...
- rpm包的安装,查询,卸载,升级,校验,数据库重建,验证数据包
rpm命名: 包:组成部分 主包:bind-9.7.1-1.i586.e15.rpm 子包:bind-lib-9.7.1-1.i586.e15.rpm bind-utils-9.7.1-1.i586. ...
- c# 线程的基本使用
创建线程 线程的基本操作 线程和其它常见的类一样,有着很多属性和方法,参考下表: 创建线程的方法有很多种,这里我们先从thread开始创建线程 class Program { static void ...