Azure Blob Storage With ASP.net Core Web API (.net core 3.1)

Hello Techies,

Today we are going to learn some amazing thing with the Azure Blob Storage and the Asp.net Core 3.1. So, let's start with a quick introduction about the Azure and Azure blob, and then we are going to move towards the Web API Solution which we are going to create. 

Overview

Azure is a Cloud Platform that provides more than one functionality. Today we are going to learn about the Cloud Storage or Blob Storage which contains the Container, and the Container which contains more than one files or folders inside it which can be accessible to the public or private as per the privacy we have applied.

Other than this, Azure has many more features, mainly to deploy our web API or other programs or console applications over there and web jobs with different criteria as we want.

ASP.net Core Solution

Now, we have a question in our mind like, what if I want to upload a static image to the azure that will be very easy? Just Google it and get the code and apply it in our solution and take it from the "wwwroot" correct?  Right, now what if I say I have a web API and there is a model which contains the user information with image which I am getting currently in a base64 and I want to deploy that without taking a chance to change model or remove image part from it and taking it into the header or somewhere else?

Yep, do the same thing again. Just Google and get the code and just apply to our solution, No doubt, that will work in some cases and not in some cases. So what we can do, we can modify just a code modify datatype of image in model and make a separate function and deploy image and return URL to the code and store it.

So, for this solution, I am going to use the swagger for the UI, and we are using the Asp.Net Core 3.1 for this solution. Also, the Main thing we require is an Azure Storage Account or Azure Container. So, if it is not already created, you can refer to this blog for end to steps for Create Storage Account And Container.

Step 1 - Create Project

This is the simple step where we just open Visual Studio 19 (you can use any version which you are using.)

Select the Asp.net core Web application or Asp.net core MVC (which suits your project solution) and click on Next.

Add the Project Information like Title and other Details and Click on Next,

In this Additional Information, select the dot net framework 3.1 which we are using for this project solution and then click on Create.

Step 2 - Install Required NPM Packages

For this project, we require several NuGet packages which we can use for this solution, which are listed below:

  • Swashbuckle. AspNetCore
  • AzureStorage
  • Blob

Install this with the NuGet package manager or call the following commands in NuGet package manager console. (Tools⇾NuGet Package Manager⇾Package Manager Console)

In the NuGet Package Manager, Go To the Browse Tab and Search the Following NuGet Packages and install it. Refer  to the following image.

  • Swashbuckle. AspNetCore
  • WindowsAzure. Storage
  • Azure. Storage. Blobs

Or open the Package Manager console. Follow the following steps, shows in image.

Execute the following commands one by one and install the required packages.

Install-Package Azure.Storage.Blobs 
Install-Package WindowsAzure.Storage
Install-Package Swashbuckle.AspNetCore

You can give the version as well to each and every command with -version <version number>. Which is an optional thing to apply.

Step 3 - Configure the Swagger

For step by step guidance of implementing Swagger, you can refer to this blog, Implement Swagger.

Step 4 - Get Azure Connection String and Azure Storage Container Name 

Here we are using the Connection String for the Azure Storage and Container name to get the URL or upload the image to the Container.

So, firstly, we are going to generate the Account Key.

  • Login to Azure.
  • Click on your Storage Account


     
  • Now in Storage Account Information, Scroll Down to "Securities+Networking" in left-menubar and click on "Access Keys".


     
  • To show the Access Key and Connection String, Click on the Show button and the key and connection string will be visible to you, and you can copy it.

Now, we have created the project, installed the NuGet Package Manager As well, and We got the Required Credentials from Azure as well. So, From here we are going to start implementing the code inside the controller for uploading the image by taking the image from the API and accessing it via Azure URL

Step 5 - Implementation of the file Upload Controller

In this step, we can use the Repository structure to Differentiate the Database Models with our Project Models and also the Services or Functions or Task we can say in the different solution. Which is the best practice for the Project. 

But, we are not going to make this Solution much complex. So, we are going to implement complete code in the controller itself.

So, firstly we are going to execute the empty project with the inbuilt created controller, and we are using the same controller by renaming it.

Following is my Controller Code for now.

using Microsoft.AspNetCore.Mvc;

namespace Demo_Upload_Image_To_Azure_Blob.Controllers
{
    [Route("api/Home")]
    [ApiController]
    public class HomeController : Controller
    {
    }
}

What I have done in this controller is I have removed all the unnecessary code and starting from the fresh and the output of this code is shown below:

Now, we are going to implement a function to generate file name or path for the file to upload with the folder name as date and then inside the file with different name.

private string GenerateFileName(string fileName, string CustomerName){
     try{
            string strFileName = string.Empty;
            string[] strName = fileName.Split('.');
            strFileName = CustomerName + DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd") + "/" 
               + DateTime.Now.ToUniversalTime().ToString("yyyyMMdd\\THHmmssfff") + "." + 
               strName[strName.Length - 1];
            return strFileName;
         }
         catch (Exception ex){
              return fileName;
         }
}

This function will generate the folder with the Customer Name with Current Date and then the file name.

Now, we are going to upload the file with the previously generated file name with path.

Firstly, we are going to create the object for the Blob Container.

BlobContainerClient container = new BlobContainerClient("Azure Connection String", "Azure Container Name");

Here, we are going to add the connection string and the container name, which we got from the above steps.

BlobClient blob = container.GetBlobClient(filename);

The above code is going to create the Blob for the file name with path as the Blob.

using (Stream stream = file.File.OpenReadStream()){
      blob.Upload(stream);
}
fileUrl = blob.Uri.AbsoluteUri;

Here, using is a statement that provides the clean code. Here stream is going to create the file stream for the Read, and we will use the blob client to upload it on the Azure, and then we will get the URL from the blob as well which returns the string URL or path where the file is uploaded.

Now, the complete code for the controller is going to be: 

[Route("uploadImage")]
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> uploadImage([FromForm] FileModel file){
     try{
             var filename = GenerateFileName(file.File.FileName, file.FileName);
             var fileUrl = "";
             BlobContainerClient container = new BlobContainerClient("Äzure Connection String", 
             "Azure Storage Container name");
             try{
                    BlobClient blob = container.GetBlobClient(filename);
                    using (Stream stream = file.File.OpenReadStream())
                    {
                        blob.Upload(stream);
                    }
                    fileUrl = blob.Uri.AbsoluteUri;
              }
              catch (Exception ex){}
              var result = fileUrl;
              return Ok(result);
          }
          catch (Exception ex){
               return Ok();
          }
}

Step 6 - Verify Output

Now, let's check the output and the Azure dashboard where we can get the file in azure.

For Swagger, upload the image and give the customer name, and now click on the Execute.

Let's first check the name of the file which is generated by the Generate File Name function which the folder name which we have made. We can check it using the debug point. We can check in the following image that we will get the file name inside the particular folder name with the current date which is created over the Azure Container if the folder is not already created.

After successful execution of this controller, we will get the complete path of the remote file, or we can say azure path inside the response. With this link or URL we can access the image remotely.

Step 7 - Check azure dashboard

Now, let's check with the Azure to check whether the folder and the blob .or file is uploaded inside that folder or not.

  • Login to Azure
  • Click on the Azure Storage
  • Click on the Containers on the Left Sidebar 
  • Click on the Container name 

You can check the folder is created with the customer name with the Date. Now, let's check the file is uploaded inside the folder or not.

Over here, we can check that the file is uploaded inside the folder. And we can access it with the remote file URL.

I hope this will be helpful to you.


Similar Articles