How to Upload Files into Azure Blob Storage with ASP.NET Core Web API

We are going to divide this article into the following sections:

  • Creating Azure Storage
  • Upload Files to Azure with ASP.NET Core Web API

Creating Azure Storage

The first thing we have to do is to navigate and sign in to Azure Portal where we can create our storage. If we don’t have a subscription, we can create a free subscription account on the dashboard.

Next, we are going to create a new storage account service:

A new storage account service is being created.

Another view of the storage creation process.

After these steps are done, we are going to click the Next button two times until our validation gets passed.

Validation completion after clicking the Next button.

We are going to modify the appsettings.json file by adding a connection string section:


{
  "ConnectionStrings": {
    "EmployeeAppcon": "Data Source=****.mysql.database.azure.com;initial catalog=databaseName;User id=****; Pwd=***",
    "AzureBlobStorage": "DefaultEndpointsProtocol=https;AccountName=authoringsite;AccountKey=X+55***3SgA==;EndpointSuffix=core.windows.net"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

We can find this connection string in the Access keys menu that we already have opened:

Location of the connection string in the Access keys menu.

Next, create a new project in Visual Studio.

Creating a new project in Visual Studio.

Select ASP.Net Core Web Application.

Selecting ASP.Net Core Web Application in Visual Studio.

Provide the Project name and location.

Entering project name and location in Visual Studio.

Select Target Framework and click on the Create button.

Selecting Target Framework and creating the project.

Once the project is created a basic view of the solution is explored.

Exploring the basic view of the solution in Visual Studio.

We need to create two folders with names controllers and models.

Creating controllers and models folders.

Need to install dependency from Genet packages.

MySql.Data.dll
Microsoft.AspNetCore.Mvc.NewtonsoftJson.dll – version 3.1.10
Azure.Storage.Blobs – version 12.1.0

Please update the below the line in startup.js

// added scope to azure blob storage
services.AddScoped(x => new BlobServiceClient(Configuration.GetValue<string>("ConnectionStrings:AzureBlobStorage")));

Next, we need to create AssetUploadController.cs

Creating AssetUploadController.cs

using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using createwebapiusingmysql.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;

namespace createwebapiusingmysql.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AssetUploadController : Controller
    {
        private readonly string _azureConnectionString;
        private readonly string _azureConnectionStringsastoken;
        private readonly IConfiguration _configuration;

        public AssetUploadController(IConfiguration configuration)
        {
            _azureConnectionString = configuration.GetConnectionString("AzureBlobStorage");
            _azureConnectionStringsastoken = configuration.GetConnectionString("SASToken");
            _configuration = configuration;
        }

        List<Products> _category = new List<Products>();

        [HttpPost("{id}")]
        public async Task<IActionResult> assetAsync(int id)
        {
            try
            {
                GetcategoryFriendlyame(id);
                string containersname = _category[0].categoryFriendlyame;
                var formCollection = await Request.ReadFormAsync();
                var file = formCollection.Files.First();

                if (file.Length > 0)
                {
                    var container = new BlobContainerClient(_azureConnectionString, containersname);
                    var createResponse = await container.CreateIfNotExistsAsync();

                    if (createResponse != null && createResponse.GetRawResponse().Status == 201)
                        await container.SetAccessPolicyAsync(Azure.Storage.Blobs.Models.PublicAccessType.Blob);

                    var blob = container.GetBlobClient(file.FileName);

                    await blob.DeleteIfExistsAsync((Azure.Storage.Blobs.Models.DeleteSnapshotsOption)Azure.Storage.Blobs.Models.DeleteSnapshotsOption.IncludeSnapshots);

                    using (var fileStream = file.OpenReadStream())
                    {
                        await blob.UploadAsync(fileStream, new BlobHttpHeaders { ContentType = file.ContentType });
                        blob.SetMetadata(new Dictionary<string, string>());

                        Dictionary<string, string> metadata = new Dictionary<string, string>(2);
                        metadata.Add("ProductId", id.ToString());
                        blob.SetMetadata(metadata);
                    }

                    if (blob.Uri.ToString() != null && blob.Uri.ToString() != "")
                    {
                        UpdateProductTable(id.ToString(), blob.Uri.ToString());
                    }

                    return Ok(blob.Uri.ToString());
                }

                return BadRequest();
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"Internal server error: {ex}");
            }
        }

        // we are getting category name to create container in azure
        private List<Products> GetcategoryFriendlyame(int id)
        {
            var @ProductId = id;
            string query = @"select categoryFriendlyame, ProductId from restapi.categories, restapi.products where categories.categoryid = products.categoryid AND products.ProductId=" + @ProductId + ";";
            DataTable table = new DataTable();
            string sqlDataSource = _configuration.GetConnectionString("EmployeeAppcon");
            MySqlDataReader myReader;

            using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
            {
                mycon.Open();
                using (MySqlCommand mycommond = new MySqlCommand(query, mycon))
                {
                    myReader = mycommond.ExecuteReader();
                    table.Load(myReader);
                    myReader.Close();
                    mycon.Close();
                }

                for (int i = 0; i < table.Rows.Count; i++)
                {
                    Products prd = new Products();
                    prd.ProductId = Convert.ToInt32(table.Rows[i]["ProductId"]);
                    prd.categoryFriendlyame = table.Rows[i]["categoryFriendlyame"].ToString();
                    _category.Add(prd);
                }
                return (_category);
            }
        }

        // We are updating image and model url to field in product table
        private void UpdateProductTable(string v1, string v2)
        {
            string imageuri = v2;
            var splitVals = imageuri.Split('/');
            var URL4 = splitVals[3];
            var URL5 = splitVals[4];
            string subseturi = "https://ceeademocontent.azureedge.net";
            var sastoken = _azureConnectionStringsastoken;
            string finalurl = "" + subseturi + "/" + URL4 + "/" + URL5 + sastoken;
            string imagetype = URL5.Substring(URL5.Length - 4);
            string query;

            if (imagetype.ToString() == "gltf" || imagetype.ToString() == ".glb")
            {
                query = @"update restapi.Products set productModel = '{finalurl}' where productId = {v1}";
                query = query.Replace("{finalurl}", finalurl);
                query = query.Replace("{v1}", v1);
            }
            else
            {
                query = @"update restapi.Products set productPreview = '{finalurl}' where productId = {v1}";
                query = query.Replace("{finalurl}", finalurl);
                query = query.Replace("{v1}", v1);
            }

            DataTable table = new DataTable();
            string sqlDataSource = _configuration.GetConnectionString("EmployeeAppcon");
            MySqlDataReader myReader;

            using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
            {
                mycon.Open();
                using (MySqlCommand mycommond = new MySqlCommand(query, mycon))
                {
                    myReader = mycommond.ExecuteReader();
                    table.Load(myReader);
                    myReader.Close();
                    mycon.Close();
                }
            }
        }
    }
}

Finally, with Postman try to add the file to Azure blob storage as shown in the below screen.

Demonstration of using Postman to add a file to Azure blob storage.