问题
如何在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存储帐户和容器。这些指令可以在这里找到