DEV Community

Cover image for Easy Guide to Azure Blob Storage for .NET Developers
Sefat Anam
Sefat Anam

Posted on

Easy Guide to Azure Blob Storage for .NET Developers

What is Azure Blob Storage ?

Azure Blob storage is Microsoft's object storage solution for the cloud. Blob storage is optimized for storing massive amounts of unstructured data. Unstructured data is data that doesn't adhere to a particular data model or definition, such as text or binary data.

Why Azure Blob Storage ?

  • Serving images or documents directly to a browser.
  • Storing files for distributed access.
  • Streaming video and audio.
  • Writing to log files.
  • Storing data for backup and restore, disaster recovery, and archiving.
  • Storing data for analysis by an on-premises or Azure-hosted service.

All of above theory from Microsoft's Documentations about Blob Storage . Now Let get into the point ,

Today we will go fast forward to see how its works rather than knowing too deep architecture, its pretty straight forward for visualize the work flow of azure blob storage.

What we will learn today ?

Today we will store a image to blob storage and retrieve it using NET5 web project.

Ingredient's

To Continue further steps sign up in Azure.

Azure Blob Storage Setup

After creating Azure Account , Open Azure Portal . In the homepage will will notice a icon named "create a resource" click it.

Home Page of Azure Portal



You will see a search bar there you type "Blob" & hit in "Storage Account" , create a storage account & set a storage account name. here I set my storage name is "blobazdemo"

Resource Creating page in Azure
Resource Creating page in Azure 2
Resource Creating page in Azure 3


So if everything goes well you will get validation passed message then create storage & waiting for deployment.
Resource Creating page in Azure 4

Running Deployment

Deployment Complete


After complete deployment, Go to resource and find container option from resource side nav options. Create a container inside it to store out images. Here I set my container name is "azdemo"

Container

Here the last steps, now we need connection string to connect our blob storage container to our API project. To again from your resource side nav option find out "Access key" follow the steps and copy the "connection string".

Access Key

That's all for now to working with azure blob storage.

Web Project Setup

We mainly focus on how we can store image in blob storage not making a fancy application. I recommend you to create 'webapp' or 'webapi' using dotnet cli its up to you.

Check available command to create new project

dotnet new --list

Now you can create your dotnet project by using this command schema,

dotnet new <TEMPLATE> [--dry-run] [--force] [-lang|--language {"C#"|"F#"|VB}]
    [-n|--name <OUTPUT_NAME>] [-o|--output <OUTPUT_DIRECTORY>] [Template options]

We will make a Service for responsible to store & retrieve image in azure blob storage, so before start making service we need to add a Nuget package in our project. By following,

dotnet add package Azure.Storage.Blobs --version 12.10.0

Know More About Azure Storage Blob Nuget Package

Let Jump into coding part πŸ˜€

  • Update your startup.cs by following,
  services.AddSingleton(x => new BlobServiceClient(PUT_YOUR_BLOB_CONNECTION_STRING));

  • Create a service class in my case I named it BlobService. You can set any name you want. Then Inject BlobServiceClient which is provid by Azure.Storage.Blobs.
 public class BlobService 
    {
        // BlobServiceClient from 'Azure.Storage.Blobs' package
        private readonly BlobServiceClient _blobClient;

        public BlobService(BlobServiceClient blobClient)
        {
            _blobClient = blobClient;
        }
}

  • Let fetch data from blob storage. its pretty straight forward.
 public async Task<IEnumerable<string>> AllBlobs(string containerName)
        {
            // allow us to get access to data inside container
            // in our senario 'containerName' will be 'azblob'
            var containerClient = _blobClient.GetBlobContainerClient(containerName);
            var files = new List<string>();
            var blobs = containerClient.GetBlobsAsync();
            await foreach (var item in blobs)
            {
                files.Add(item.Name);
            }
            return files;
        }
  • Upload Image into blob storage
        public async Task<bool> UploadBlob(string name, IFormFile file, string containerName)
        {
          // in our senario 'containerName' will be 'azblob'
            var containerClient = _blobClient.GetBlobContainerClient(containerName);
            // checking is current file is exit; if exit then ovverrite
            var blobClient = containerClient.GetBlobClient(name);

            var httpHeaders = new BlobHttpHeaders()
            {
                ContentType = file.ContentType
            };

            var res = await blobClient.UploadAsync(file.OpenReadStream(), httpHeaders);

            if (res != null) return true;
            return false;
        }

Here The Complete Code of Service

  • Now, We should trigger these method from controller right. Get into it, Post an image through API. [ Here I used basic mvc app to also display updated image ]
 [HttpPost]
        public async Task<IActionResult> AddFile(IFormFile file)
        {
            if (file == null || file.Length < 1) return View();
            var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
            var res = await _service.UploadBlob(fileName, file, "azdemo");

            if (res) return RedirectToAction("Index");

            return View();
        }

After Successfully Posting image via API go to Azure Portal and open azdemo container you can see their a image file is created.

  • Click on the view from given options.

Click on Options

  • Finally your image is there.

Image View

Here The Complete Code of Controller

That's all for today. Hope now you can easily complete rest of the functionality your self.

Happy Coding
I’m Sefat Anam
Full-Stack Developer ( Angular, .NET )
Email: sefatanam@outlook.com

Top comments (1)

Collapse
 
sefatanam profile image
Sefat Anam

I will keep updating this article, so keep following. Thanks