This is an amazing experience for me to work with Azure Blob Storage in Asp.Net MVC application. I am going to share some advance part which I have learned.
As we all know that Azure Blob Storage is used to storing the Binary Large Objects [Blobs]. Here we can store and retrieve different kinds of the data like images, documents, media files etc.
Agenda of this Article
- What is Blob Storage?
- Why Blob Storage?
- Create Blob Storage Account
- Install and Use Azure Explorer
- Create Asp.Net MVC Application
- Install Storage Client Library and Configuration through NuGet
- Upload Image through Asp.Net MVC Application
MORE ARTICLES ON ASP.NET CORE WHICH YOU MAY LIKE.
How to create and connect SQL Server and Database on Windows Azure
Azure Web App: Create, Connect and Deploy using FTP
Publish an Asp.Net Core 2.0 Application on Azure
Windows Azure Mobile Service Vs WEB API
How to create Virtual Machine in Windows Azure step by step
What is Blob Storage?
Windows Azure Blob Storage can store the hundreds of terabytes of data in one account. As you know you can create multiple blob storage account, so definitely you can store multiple hundreds of terabytes data with Windows Azure Blob Storage.
We don’t require taking tension about the backup of the data which is stored on blob storage. It is because it automatically takes the back up the data. You can increase your storage as per requirement and you need to pay only which you have used and what you have used.
One more thing, I want to consider here that you don’t need to take a headache about how to manage your data, your VM or any other things; actually Windows Azure manages everything automatically.
You can use Blob Storage as REST API and can use with any language like Java, .Net etc. Actually, technology doesn’t matter with blob storage. It means all kinds of the client can be accessible to this storage.
Why Blob Storage?
Persistency is the main advantage because we use Blob Storage. Actually, there is many ways to share your static content or files to someone. You can store it on Hard Drive but these instances are not persistent. If you are going to use VMs then it is managed automatically by Windows Azure and you don’t need to worry about this.
So, basically, you are going to put your data in persistent store for long-term uses then you need to go with Blob Storage.
Create Blob Storage Account
There are different kinds of the storage with Windows Azure like Tables Storage, Queue Storage as well as Blob Storage. Today we are going to work with Blob Storage.
To start with Blob Storage, first, you should have an Azure Account as well as Blob Storage account. If you don’t have the Windows Azure Account, you can try with Free Trial.
https://azure.microsoft.com/en-us/pricing/free-trial/
If you have MSDN subscription then you can take benefits to your credit limits.
To login with Windows Azure Portal, you just need to go with Azure portal
https://manage.windowsazure.com
Provide your credentials to log in and enter the Portal.
When you complete you successful login with Azure Portal then you will go to following page [See the below image].
To create a Blob Storage account, click to the New option which is resided in the below;
When you click to New then choose Data Service option then choose Storage > Quick Create.
It will give you the window where you can enter your blob storage URL and location [which region you want to create your blob storage]. So, here you need to provide the storage name in URL textbox. One thing you need to consider here that name is globally unique. When you are going to choose your blob storage location, please note that it will be your primary location where your blob storage data center will reside.
Below you will find one more option “Geo Replication”. If you select this option, the replica of your data will be stored in a different location in the same region. Now it is time to create your Blob Storage. So, click on CREATE STORAGE ACCOUNT.
It will take a few minutes to create and configure your storage account. Actually, it creates all types of setting for your storage account.
After a few minutes, you will find that your storage account was created successfully. You will get a successfully created message in status bar.
From the below status bar menu, you can find one more option there and it is “MANAGE ACCESS KEYS”. Actually, we need an access key to work with the storage account.
So, click on the Manage Access Keys which is resided at bottom of the screen.
Here you will see that two types of the access key, one is primary and the other one is secondary corresponding to your storage account. You can copy your storage account access key to click on Copy icon at the right side. If you think that someone knows the storage access key then you can regenerate the access key using the “regenerate” option.
So, finally, we have successfully created the storage account on Windows Azure. Now it is time to access the account. There are different types of way to access your blob storage.
Install and Use Azure Explorer
If you are working with Windows Azure Blob Storage and storing some files then you need to view, rename, and delete the files. So, you can use the Azure Explorer to access your blob storage.
You have to install Azure Explorer to your system to direct access to your blob storage. So, you can use the following link to download your azure explorer.
http://www.cerebrata.com/products/azure-explorer/introduction
Click on Download, within a few seconds, you will get the setup file for Azure Explorer. Click on the setup file to run the setup and it will be going to install the Azure Explorer for you.
When it will be installed successfully, an application icon will be set inside the program menu. Go to start and find Azure Explorer and click on it.
It will ask for license terms and conditions. You need to check on the checkbox and click on I Accept.
So, you have installed Azure Explorer successfully. It will open the azure explorer for you as follows. Here you will find the Azure Storage Account option where you will be finding the entire containers which contain the blob for you.
To add your account with Azure Explorer, Right Click on Azure Storage Account and choose Add Connection to Azure Storage.
It will provide you a different way to connect with the storage account. You need to choose “Connect to Azure with a Storage Account Name and an Access Key”. As we know that we have got access key earlier and click to Next.
In the next “Add Windows Azure Storage Account”, provides you with storage account name and storage access key.
If you want to test your connection, you can use “Test Connection” button.
So, finally, we have added our account with Azure Explorer. You can see my storage account “mukeshdemostorage” has added successfully.
As we all know that there should be a container to store the blob inside storage account. So, for creating the new container for blob, Right Click on your storage account “mukeshdemostorage” and choose New Blob Container.
It will open a dialog window where you can specify the name of the Blob Container and Access Level. I am going to provide the name as “sampleimage” [Name always should be in small letters] and there access level as Private.
So, it will create a blob container “sampleimage” for me. As it is an azure explorer. You can directly paste the documents or files inside it. I am going to paste [Upload] one of my images directly inside the “sampleimage” blob container.
So, you can see that there is one image is available with name “Mukesh Kumar”. Right click on the image and click on Copy Path. It will directly copy the path of image which is resided on the server.
Going to access the image, you can paste the URL inside the browser and press enter. You will see following error which says that you can’t access this file because of the access level of this file is Private and you can’t access it from outside as publically.
So, you need to change the access level of your blob container.
When you again try to access the same URL inside the browser, you will find the image is uploaded through the Azure Explorer.
Create Asp.Net MVC Application
We have successfully uploaded and access the same image from Azure Explorer. It is very easy. But how it is possible through an application, so, complete this task I am going to create an MVC application from where I will try to upload an image inside the blob storage and access it.
So, create an MVC application “BlobStorageDemo” with No Authentication.
As I am going to upload an image, to create a controller “ImageController” from where we will perform all the activity of the image. Right Click on the Controller < Add < Controller.
Provide the name of the Controller as “ImageController” and click to Add.
using System.Web.Mvc;
namespace BlobStorageDemo.Controllers
{
public class ImageController : Controller
{
ImageService imageService = new ImageService();
// GET: Image
public ActionResult Upload()
{
return View();
}
}
}
Install Storage Client Library and Configuration through NuGet
Generally, when we create the simple application there is no reference of the Storage Client Library. So to add this I am going to use NuGet Package Manager.
Right Click on the project and choose Manage NuGet Packages.
It will open NuGet Package Manager for you. Typed the Azure storage inside the search and it will give you the following package which can be installed. You need to choose WindowsAzureStorage and click to Install.
It will give you some preview of what it is going to install packages.
It will take few minutes to install. When it will install successfully, you will be finding the lots of extra references inside the Reference section along with WindowsAzure.Storage.
You can also install Azure Configuration to access the configuration setting in the application.
Upload Image through Asp.Net MVC Application
So, going to access the blob storage through your services or controller, you need to use blob storage access key. So, for the security purpose, you can store it inside the configuration files. Later we can access it anytime from anywhere.
I am going to create a class “ConnectionString.cs” from where I will access the storage account name and storage access key and create the connection string for blob storage. Please make sure you need to use two namespaces
using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;
ConnectionString.cs
using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;
using System;
namespace BlobStorageDemo
{
public static class ConnectionString
{
static string account = CloudConfigurationManager.GetSetting("StorageAccountName");
static string key = CloudConfigurationManager.GetSetting("StorageAccountKey");
public static CloudStorageAccount GetConnectionString()
{
string connectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", account, key);
return CloudStorageAccount.Parse(connectionString);
}
}
}
To accessing the Storage Account, You can access it through the CloudStorageAccount class which can be accessed by account name and access key. Using the instance of the CloudStorageAccount, you can access and create the instance of the CloudBlobClient. But without accessing the blob container you can’t access the resource which is resided in a container. So, in this case, we need to use the CloudBlobContainer.
CloudStorageAccount cloudStorageAccount = ConnectionString.GetConnectionString();
CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("sampleimage");
To access these Storage classes, you make sure you are adding the following namespace.
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
ImageService.cs
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
namespace BlobStorageDemo
{
public class ImageService
{
public async Task<string> UploadImageAsync(HttpPostedFileBase imageToUpload)
{
string imageFullPath = null;
if (imageToUpload == null || imageToUpload.ContentLength==0)
{
return null;
}
try
{
CloudStorageAccount cloudStorageAccount = ConnectionString.GetConnectionString();
CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("sampleimage");
if(await cloudBlobContainer.CreateIfNotExistsAsync())
{
await cloudBlobContainer.SetPermissionsAsync(
new BlobContainerPermissions {
PublicAccess = BlobContainerPublicAccessType.Blob
}
);
}
string imageName = Guid.NewGuid().ToString() + "-" + Path.GetExtension(imageToUpload.FileName);
CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(imageName);
cloudBlockBlob.Properties.ContentType = imageToUpload.ContentType;
await cloudBlockBlob.UploadFromStreamAsync(imageToUpload.InputStream);
imageFullPath = cloudBlockBlob.Uri.ToString();
}
catch (Exception ex)
{
}
return imageFullPath;
}
}
}
As we are going to upload and show the latest uploaded image on the view, we need to make changes in the controller as follows. I am going to upload the image through the “Upload” Action and showing the latest image through the action “LatestImage”
ImageController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace BlobStorageDemo.Controllers
{
public class ImageController : Controller
{
ImageService imageService = new ImageService();
// GET: Image
public ActionResult Upload()
{
return View();
}
[HttpPost]
public async Task<ActionResult> Upload(HttpPostedFileBase photo)
{
var imageUrl= await imageService.UploadImageAsync(photo);
TempData["LatestImage"] = imageUrl.ToString();
return RedirectToAction("LatestImage");
}
public ActionResult LatestImage()
{
var latestImage = string.Empty;
if (TempData["LatestImage"] != null)
{
ViewBag.LatestImage = Convert.ToString(TempData["LatestImage"]);
}
return View();
}
}
}
To upload and show the latest image, I have created two different views. For the uploading, you can you upload.cshtml and for showing the latest image you can use LatestImage.cshtml.
Upload.cshtml
@{
ViewBag.Title = "Upload";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Upload Image</h2>
<br />
@using (Html.BeginForm("Upload", "Image", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<fieldset class="form-horizontal">
<div class="form-group">
<label class="control-label col-md-2" for="Photo">Photo</label>
<div class="col-md-10">
<input type="file" name="photo" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Submit" class="btn" />
</div>
</div>
</fieldset>
}
LatestImage.cshtml
@model string
@{
ViewBag.Title = "Latest Image";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<br />
<h3>Latest Uploaded Image</h3>
<br />
<img src="@ViewBag.LatestImage" title="Latest Uploaded" />
It is time to run the project. So, runt the project to press F5 and go to the following page to upload the image, here you can choose an image which is going to upload and click to submit.
When you click to submit, it will upload your image inside the sampleimage blob storage container. And redirect to latest image page with the latest uploaded image.
You can check to upload an image to refresh the Azure Explorer.
Conclusion
So, today we have learned what blob storage is and why we need to use it. We have used blob storage to create an account with Asp.Net MVC application.
Suggest, what do you think?
Thanks for reading this article, hope you have enjoyed it. Please share your valuable feedback and suggestion through comments. If I have missed any point or please add your points if you can make it better for readers, you are most welcome.
Posted Comments :
Mukesh Kumar Author Posted : 9 Years Ago
Thanks Nitin for your valuable comment,
Einar A. Posted : 8 Years Ago
Hello, I am going through this tutorial. I've come across an issue when I tried to run it. The error is as follows: Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Source Error: Line 20: public async Task<ActionResult> Upload(HttpPostedFileBase photo) { Line 21: var imageUrl = await imageService.UploadImageAsync(photo); Line 22: TempData["LatestImage"] = imageUrl.ToString(); Line 23: return RedirectToAction("LatestImage"); Line 24: }
Ayush Bansal Posted : 5 Years Ago
It worked perfectly. Thankyou sir.
CloudStakes Technology Posted : 3 Years Ago
Nice Information! This information is relevan to lateste technology.
Nitin Tyagi Posted : 9 Years Ago
Very well written. Thanks for sharing!! Looking forward for more articles.