Azure Blob Storage with ASP.NET MVC

How to work with Azure Blob Storage and ASP.NET MVC

Blob Storage is a part of Microsoft Azure platform. We can use Azure Blob Storage to store our unstructured data in the cloud as objects. We can store files like text files, media files, documents etc.

In this article we are discussing about how to use blob storage to store files through an ASP.NET application. As the first step we need to create a cloud account in Azure cloud. There are two types of accounts available. General-purpose storage account or a Blob storage account. If you don’t want to create any account and still you want to develop an application for testing purpose then still there is a way. You can use the storage emulator. The storage emulator is a local environment that emulates an Azure Storage account in the cloud.

If you are going to develop an application for testing purpose, I suggest to use emulator. Anyway in here I’m going to discuss both emulator and the actual storage account.

What is Blob Storage?

As mentioned above blob storage is a cloud platform to store files and its a service from Microsoft Azure.

  • Storage Account: There should be a storage account to access the files. 2 types of storage accounts General-purpose storage account or a Blob storage account which is unique for storing blobs.
  • Container: Containers provide grouping of blobs. All blobs must be inside a blob container.
    • A container can store an unlimited number of blobs.
    • Container names must be lowercase.
  • Blob: Is a file of any type and any size. Azure Storage offers three types of blobs:
    • block blobs,
    • page blobs
    • append blobs.Block blobs are ideal for storing text or binary files, such as documents and media files.Append blobs are similar to block blobs in that they are made up of blocks, but they are optimized for append operations, so they are useful for logging scenarios. A single block blob can contain up to 50,000 blocks of up to 100 MB each, for a total size of slightly more than 4.75 TB (100 MB X 50,000). A single append blob can contain up to 50,000 blocks of up to 4 MB each, for a total size of slightly more than 195 GB (4 MB X 50,000).Page blobs can be up to 1 TB in size, and are more efficient for frequent read/write operations. Azure Virtual Machines use page blobs as OS and data disks.

Here we are going to use only block blobs.

Since we need a storage account, you can create an account from https://portal.azure.com

Create ASP.NET application

We will create an ASP.NET MVC application using Visual Studio. So as the first step just create a new project which is ASP.NET MVC using VS.

Then add a new action in HomeController and add a new view for that action.

public ActionResult BlobStorage()
{
return View();
}

We can view this new view by going to localhost/home/blobstorage url.

Now we have to use Azure Storage Client Library in our application. So add some nuget packages for the solution.

azure config manager

azure storage

Now we have the required packages with our solution. Next step is to change the action and view to facilitate a file upload function.

Create a Post action for the BlobStorage action and add a new parameter to get the file to controller. Parameter type is HttpPostedFileBase and I’m using “FileUpload” as parameter name.

Now we have to modify the view to include a form inside the view.

This is the code for the view

@{
ViewBag.Title = "Blob storage";
}
<h2>@ViewBag.Title.</h2>
@using (Html.BeginForm("BlobStorage", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div><input type="file" name="FileUpload" /></div>
<div class="form-row">
<input type="submit" value="Submit" />
</div>
}

Make sure to add the part enctype = “multipart/form-data” inside the begin form, otherwise the file will not be posted to the controller.

For the file upload control we are using a normal file input and the input name should be same as the Post action parameter name.

Now we have to create the BlobStorageManager class to manage file handling. So for this we can create a new class called “BlobStorageManager” and add below directives

using Microsoft.WindowsAzure.Storage; // Namespace for CloudStorageAccount
using Microsoft.WindowsAzure.Storage.Blob; // Namespace for Blob storage types
using Microsoft.WindowsAzure; // Namespace for CloudConfigurationManager

Initialize the Azure Blob Storage account

protected CloudStorageAccount InitializeAccount()
{
  CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
  CloudConfigurationManager.GetSetting("StorageConnectionString"));
  return storageAccount;
}

In here we are taking the storage account details from the web.config. so we need to add the storage connection string to the web config file

<add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=youraccountname;AccountKey=a7xvrc+1cwrHidB+tRueLoveNev3rDi3YWq==;EndpointSuffix=core.windows.net" />

if you want to use only emulator the just use as below

protected CloudStorageAccount InitializeAccount()
{
   return CloudStorageAccount.DevelopmentStorageAccount;
}

To use the development Storage Account you have to first install the Storage Emulator and run it. Otherwise it will give you errors.

Then add method to upload the file

public void UploadFile(string containerName, HttpPostedFileBase file)
 {
  var container = this.GetContainer(containerName);

  CloudBlockBlob blockBlob = container.GetBlockBlobReference(file.FileName);
  blockBlob.Properties.ContentType = file.ContentType;
  Stream inputFileStream = file.InputStream;
  using (var fileStream = inputFileStream)
  {
   blockBlob.UploadFromStream(fileStream);
  }
 }

and also write a method to Get the container by name. Each and every file should be inside a blob container. So we need to create a blob container inside our storage space.

public CloudBlobContainer GetContainer(string containerName)
 {
 CloudBlobClient blobClient = InitializeAccount().CreateCloudBlobClient();
 CloudBlobContainer container =  blobClient.GetContainerReference(containerName);
 container.CreateIfNotExists();

 return container;
 }

In this method we are creating the Blob container if its not existing. Here is the full code for the Manager class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.WindowsAzure; // Namespace for CloudConfigurationManager
using Microsoft.WindowsAzure.Storage; // Namespace for CloudStorageAccount
using Microsoft.WindowsAzure.Storage.Blob; // Namespace for Blob storage types
using Microsoft.Azure;
using System.IO;

namespace BlobStorage
{
 public class BlobStorageManager
 {
 protected CloudStorageAccount InitializeAccount()
 {
 //CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
 //CloudConfigurationManager.GetSetting("StorageConnectionString"));
 //return storageAccount;

return CloudStorageAccount.DevelopmentStorageAccount;
 }

public CloudBlobContainer GetContainer(string containerName)
 {
 CloudBlobClient blobClient = InitializeAccount().CreateCloudBlobClient();
 CloudBlobContainer container = blobClient.GetContainerReference(containerName);
 container.CreateIfNotExists();

return container;
 }

/// <summary>
 /// Upload a file into the specified container
 /// </summary>
 /// <param name="containerName"></param>
 /// <param name="file"></param>
 public void UploadFile(string containerName, HttpPostedFileBase file)
 {
 var container = this.GetContainer(containerName);

CloudBlockBlob blockBlob = container.GetBlockBlobReference(file.FileName);
 blockBlob.Properties.ContentType = file.ContentType;
 Stream inputFileStream = file.InputStream;
 using (var fileStream = inputFileStream)
 {
 blockBlob.UploadFromStream(fileStream);
 }
 }
 }
}

Then modify the Post action in controller to get the file and pass to manager.

[HttpPost]
public ActionResult BlobStorage(HttpPostedFileBase FileUpload)
{
  if (FileUpload != null && FileUpload.ContentLength > 0)
  {
   var blobManager = new BlobStorageManager();
   blobManager.UploadFile("mysamplecontainer", FileUpload);
  }

  return View();
 }

In here I’m specifying the container as “mysamplecontainer”, so the file will be uploaded to the mysamplecontainer container.

Now we can run the application and go to the upload page.

After submitting the file you can see the file inside the container in you cloud storage. We can use Storage Explorer tool to view the files inside the containers. We will see how to List and download the files in next article.

2 thoughts on “Azure Blob Storage with ASP.NET MVC

  1. Hi Sajith,
    Thanks for this article it is very useful.
    Any info on download using sas key?
    Thanks,
    Mani

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.