Mastering Azure Blob Storage with ASP.NET Core MVC

Introduction

Azure Blob Storage is a scalable object storage service for unstructured data, such as text or binary data. It's designed to store large amounts of data, including images, documents, media files, and backup data. Azure Blob Storage provides a cost-effective and highly available storage solution, making it ideal for various applications like content distribution, data backup, and big data analytics.

Key features of azure blob storage

  1. Scalability: Store petabytes of data and handle millions of requests per second.
  2. Security: Provides encryption at rest and in transit, along with fine-grained access control.
  3. High Availability and Durability: Offers 99.999999999% durability for objects and multiple replication options.
  4. Integration: Easily integrates with other Azure services, including Azure CDN, Azure Data Factory, and Azure Machine Learning.
  5. Cost-Effective: Offers various storage tiers (hot, cool, and archive) to optimize costs based on access patterns.
  6. Data Management: Supports lifecycle management policies to automate data retention and deletion.

Pros of Azure blob storage

  1. Cost-Efficiency: Pay only for the storage you use, with different tiers for different access needs.
  2. Scalability: Easily scale storage capacity and performance to meet your needs.
  3. Accessibility: Access your data from anywhere in the world via HTTP/HTTPS.
  4. Security: Advanced security features ensure data protection and compliance with industry standards.
  5. Integration: Seamlessly integrates with other Azure services and third-party applications.
  6. Data Management: Automated lifecycle management helps manage data efficiently.

Cons of Azure blob storage

  1. Complexity: Learning to manage and optimize blob storage for specific use cases can be complex.
  2. Costs for Frequent Access: Frequent access to data in lower-cost tiers (cool and archive) can incur additional costs.
  3. Latency: Accessing data from geographically distant regions may introduce latency.
  4. Limited Querying Capabilities: Not designed for complex querying or transactional operations.

Integration with ASP.NET Core MVC

Integrating Azure Blob Storage with an ASP.NET Core MVC application involves several steps.

1. Setting up Azure blob storage

  1. Create a Storage Account: Go to the Azure portal and create a new storage account.
  2. Get Connection String: Retrieve the connection string from the Azure portal for use in your application.

2. Configuring ASP.NET core MVC project

  • Install NuGet Packages: Install the necessary NuGet packages for Azure Blob Storage in your ASP.NET Core MVC project.
    dotnet add package Azure.Storage.Blobs
    
  • Add Configuration: Add the storage account connection string to your appsettings.json.
    {
        "AzureBlobStorage": {
            "ConnectionString": "DefaultEndpointsProtocol=https;AccountName=<your-account-name>;AccountKey=<your-account-key>;EndpointSuffix=core.windows.net"
        }
    }
    
  • Images Controller: This controller shows all the blob images inside the my-images-profile container and shows them in the table inside the Index page. The controller also handles blob upload and preview features as well.
    public class ImagesController : Controller
    {
        private readonly BlobServiceClient _blobClient;
        private readonly BlobContainerClient _containerClient;
        const string ContainerName = "my-images-profile";
        public ImagesController()
        {
            _blobClient = new BlobServiceClient("UseDevelopmentStorage=true");
            _containerClient = _blobClient.GetBlobContainerClient(ContainerName);
            _containerClient.CreateIfNotExists();
        }
        // GET: ImagesController
        public ActionResult Index()
        {
            var blobs = _containerClient.GetBlobs();
            return View(blobs);
        }
        // GET: ImagesController/Details/5
        public ActionResult Details(string blobName)
        {
            var blobClient = _containerClient.GetBlobClient(blobName);
            var url = blobClient.GenerateSasUri(Azure.Storage.Sas.BlobSasPermissions.Read, DateTimeOffset.UtcNow.AddDays(1));
            ViewBag.url = url;
            return View();
        }
        // GET : Downloading file
        public ActionResult Download(string blobName)
        {
            var blobClient = _containerClient.GetBlobClient(blobName);
    
            var ms = new MemoryStream();
            blobClient.DownloadTo(ms);
            ms.Position = 0;
    
            return File(ms, "application/octet-stream", blobName);
        }
        // GET: ImagesController/Upload
        public ActionResult Upload()
        {
            return View();
        }
        // POST: ImagesController/Upload
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Upload(IFormFile file)
        {
            try
            {
                if (file is null || file.Length == 0)
                {
                    return BadRequest();
                }
                _containerClient.UploadBlob(file.FileName, file.OpenReadStream());
                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }
        // POST: ImagesController/Delete/5
        [HttpGet]
        public ActionResult Delete(string blobName)
        {
            try
            {
                var blobClient = _containerClient.GetBlobClient(blobName);
    
                blobClient.DeleteIfExists();
    
                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }
    }
    
  • Index view: Create Index.chstml view inside the Image folder inside views. This will show all the files inside the container.
    @using Azure.Storage.Blobs.Models
    @model Azure.Pageable<BlobItem>
    <table class="table table-bordered">
        <tr>
            <th>Blob Name</th>
            <th>Actions</th>
        </tr>
        @foreach (var item in Model)
        {
            <tr>
                <td>@item.Name</td>
                <td>
                    <a asp-action="Details" asp-route-blobName="@item.Name">Preview</a>
                    <a asp-action="Download" asp-route-blobName="@item.Name">Download</a>
                    <a asp-action="Delete" asp-route-blobName="@item.Name">Delete</a>
                </td>
            </tr>
        }
    </table>
    
  • Details view: Create Upload. cshtml file inside the Image folder inside views. This page shows the image directly.
    <img src="@ViewBag.url" />
  • Upload view: Create Upload. cshtml file inside the Image folder inside views. This form uploads an image and posts it to ASP.NET Core MVC Action.
    <form asp-action="Upload" enctype="multipart/form-data">
        <input type="file" name="file" class="form-control" />
    
        <button type="submit">Save</button>
    </form>

Conclusion

Azure Blob Storage is a powerful, scalable, and cost-effective storage solution for unstructured data. Integrating it with an ASP.NET Core MVC application is straightforward, allowing developers to build robust applications that can handle large amounts of data efficiently. By following the steps outlined above, you can leverage Azure Blob Storage's capabilities to enhance your web applications with secure and scalable storage solutions.

Source Code

You can access the code from my AzureEssentialSeries Github Repo. Please give it a start if you like it.

Video Tutorial

You can watch the Azure Essentials show Episode 3 on CSharpTV for this topic. You can also watch this video on my LinkedIn.


Finchship
We Provide Web, Desktop and Mobile Apps Solution