Upload Files🗒️ In Azure Blob Storage Using ASP.NET Core

Today, in this article, we will discuss how to develop a web application to store uploaded files into the Azure Blob Storage. Now, as we all know, Blob Storage is a part of the Azure Storage. So, first, we will discuss some basic concepts about Azure Storage and then, we will discuss how to store file data into the Azure Blob Storage. The Code example contains the both version of Asp.Net Core i.e. 2.1 and 3.1.
 

Definition of Azure Storage

 
Microsoft provides different ways to store data or information in Azure. We can use different database types like Azure SQL Server, Azure Cosmos DB, or Azure Table Storage. Also, we can use either Azure Queues or Event Hubs for storing and sending a message like an Email, SMS, etc. In the same way, we can use either Azure Files or Azure Blob Storage to store files in Azure. Normally Azure Storage contains four different data services. These four data services place together as a group and are named Azure Storage. Azure storage consists of Azure Blobs, Azure Files, Azure Queues, and Azure Tables. These four data storage services are always available in special consideration because they all are primitive and cloud-based storage services and can be used together in the same application. The below image shows all the elements of Azure Storage.
 
Upload Files In Azure Blob Storage Using ASP.NET Core 
 

Storage Account

 
In Azure, Storage Account always acts as a container that consists of a multiple set of Azure Storage Service together. In Storage Account, only data services from the Azure Storage group can be included like Azure Blobs, Files, Queues, and Tables. So, basically, it acts as a group which contains multiple data services of Azure Storage. The below image demonstrates the basic concept of Azure Storage Accounts.
 
Upload Files In Azure Blob Storage Using ASP.NET Core 
 

Prerequisites

  1. Microsoft Visual Studio 2017
  2. Account in Azure Portal.
If you don’t have any existing Azure account, then you can create a free trial account in the Azure portal using your email id. 
 

Create an Azure Storage Account

 
To create the Azure Storage Account in Azure Portal, first, you need to log in to the Azure Portal and then perform the below steps.
 
Step 1
 
Click on the Azure Storage Accounts option from the Resource Dashboard.

Upload Files In Azure Blob Storage Using ASP.NET Core

Step 2
 
On the Create Azure Storage Account, click on the Add button on the Storage Account page.
 
Upload Files In Azure Blob Storage Using ASP.NET Core 

Step 3
 
Now, provide the related required information to create an Azure Storage account.
 
Upload Files In Azure Blob Storage Using ASP.NET Core 

Step 4
 
In the above image, Storage Account Name means Account Name. Also, select Storage V2 options for availing the service of all four data services of Azure Storage Accounts.
 
Step 5
 
Now, click the "Review and Create" button.
 
Step 6
 
After the settings are validated, click "Create" to create the account.
 
Step 7
 
The account creation takes some time. Wait for the portal to display the notification telling that the deployment succeeded and click the notification.
 
Step 8
 
Once the deployment is succeeded, click the "Go to resource" option to open Storage Account.
 
Step 9
 
Once Storage Account is created, click on Access Keys options of the left panel and copy the ConnectionString value. This value is needed to be provided in our web application so that we can upload files in Azure Blob Storage.
 
Upload Files In Azure Blob Storage Using ASP.NET Core 
 

Create a Web Application using ASP.NET Core in Visual Studio

 
Step 1
 
Now, open Microsoft Visual Studio 2017 and click on File --> New --> Projects.
 
Upload Files In Azure Blob Storage Using ASP.NET Core 

Step 2
 
Select the Web Application project template and click the OK button.
 
Upload Files In Azure Blob Storage Using ASP.NET Core 

Step 3
 
In the Project Template box, select Web Application (Model-View-Controller) options and click on the OK button.
 
Step 4
 
Now a blank project solution is ready.
 
Step 5
 
First, open the App.Config file and store the connections string to this file which we already copied from the Azure portal. 
  1. {  
  2.   "Logging": {  
  3.     "LogLevel": {  
  4.       "Default""Warning"  
  5.     }  
  6.   },  
  7.   "AllowedHosts""*",  
  8.   "BlobConnections""",  
  9.   "ConnectionStrings": {  
  10.     "AccessKey""DefaultEndpointsProtocol=https;AccountName=testblobdump;AccountKey=ADSSADS222SSDbfOcGSuHbKnTlExh3kieXy6zwMZ/F3vDnOGT1uV5oy1KEYZ3ui6WFhayHC5tLkCA==;EndpointSuffix=core.windows.net"  
  11.   }  
  12. }  
Step 6
 
Now, add another Class Library Project to create the Service Layer.
 
Step 7
 
After adding the new projects, we need to install the below NuGet Packages to access the Azure Storage account using Windows Azure Storage client driver.
 
Upload Files In Azure Blob Storage Using ASP.NET Core 

Step 8
 
Now, add another class library project for Data Context and add a class called Products and define the Product model class as below.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.ComponentModel.DataAnnotations.Schema;  
  5. using System.Text;  
  6. using Microsoft.AspNetCore.Http;  
  7.   
  8. namespace DataContext.Models  
  9. {  
  10.     [Table("Product", Schema = "Core")]  
  11.     public class Product  
  12.     {  
  13.         public Product()  
  14.         {  
  15.             CreatedDate = DateTime.Now;  
  16.         }  
  17.   
  18.         [Key]  
  19.         public int ProductId { getset; }  
  20.   
  21.         [Required(ErrorMessage = "Please Enter Name")]  
  22.         [Column(TypeName = "varchar(50)")]  
  23.         public string Name { getset; }  
  24.   
  25.         public decimal UnitPrice { getset; }  
  26.   
  27.         [Required(ErrorMessage = "Please Enter Description")]  
  28.         [Column(TypeName = "varchar(500)")]  
  29.         public string Description { getset; }  
  30.   
  31.         [Column(TypeName = "varchar(50)")]  
  32.         public string ImageName { getset; }  
  33.   
  34.         [Column(TypeName = "varchar(250)")]  
  35.         public string ImagePath { getset; }  
  36.   
  37.         public DateTime CreatedDate { getset; }  
  38.   
  39.         public DateTime? UpdatedDate { getset; }  
  40.   
  41.         [NotMapped]  
  42.         public IFormFile File { getset; }  
  43.     }  
  44. }  
Step 9
 
Now, select the Service Layer Projects and Create a New Folder called AppConfig.
 
Step 10
 
Now, within this folder, add a new class file called AppConfiguration.cs where we will read the configuration file value by providing the key as below. 
  1. using Microsoft.Extensions.Configuration;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.IO;  
  5. using System.Text;  
  6.   
  7. namespace ServiceLayer.AppConfig  
  8. {  
  9.     public static class AppConfiguration  
  10.     {  
  11.         private static IConfiguration currentConfig;  
  12.   
  13.         public static void SetConfig(IConfiguration configuration)  
  14.         {  
  15.             currentConfig = configuration;  
  16.         }  
  17.   
  18.   
  19.         public static string GetConfiguration(string configKey)  
  20.         {  
  21.             try  
  22.             {  
  23.                 string connectionString = currentConfig.GetConnectionString(configKey);  
  24.                 return connectionString;  
  25.             }  
  26.             catch (Exception ex)  
  27.             {  
  28.                 throw (ex);  
  29.             }  
  30.             return "";  
  31.         }  
  32.   
  33.     }  
  34. }  
Step 11
 
Now, add another class called BlobStorageService.cs and add the below code. This service is basically responsible to store the uploaded file byte contained in the Azure Blob Storage. When it will upload the file in blob storage, it first creates a container called Upload and then within the container create a logical folder with the current date, and then within that logical folder original file will be stored. But in this case, we need to remember one thing very clearly that in Azure Blob Storage, there is no option for creating a folder. We can divide uploaded files logically in a date-wise, month-wise, or year wise subgrouping. This can be done with the help of the file name.
 
For example, suppose we provide a file name like this,
  1. String filename = “01-Jan-2019/abcwelcome.pdf”  
In this case, when this particular file is uploaded in Azure Blob Storage, then Azure creates a logical group named “01-Jan-2019” and then stores the file abcwelcome.pdf within that logical group. But, in normal view as from the Azure portal, it will display just like folder file structure the same as windows explorer.
 
BlobStorageService.cs 
  1. using Microsoft.WindowsAzure.Storage;  
  2. using Microsoft.WindowsAzure.Storage.Blob;  
  3. using ServiceLayer.AppConfig;  
  4. using System;  
  5. using System.Collections.Generic;  
  6. using System.IO;  
  7. using System.Threading.Tasks;  
  8.   
  9. namespace ServiceLayer  
  10. {  
  11.     public class BlobStorageService  
  12.     {  
  13.         string accessKey = string.Empty;  
  14.   
  15.         public BlobStorageService()  
  16.         {  
  17.             this.accessKey = AppConfiguration.GetConfiguration("AccessKey");  
  18.         }  
  19.   
  20.         public string UploadFileToBlob(string strFileName, byte[] fileData, string fileMimeType)  
  21.         {  
  22.             try  
  23.             {  
  24.   
  25.                 var _task = Task.Run(() => this.UploadFileToBlobAsync(strFileName, fileData, fileMimeType));  
  26.                 _task.Wait();  
  27.                 string fileUrl = _task.Result;  
  28.                 return fileUrl;  
  29.             }  
  30.             catch (Exception ex)  
  31.             {  
  32.                 throw (ex);  
  33.             }  
  34.         }  
  35.   
  36.         public async void DeleteBlobData(string fileUrl)  
  37.         {  
  38.             Uri uriObj = new Uri(fileUrl);  
  39.             string BlobName = Path.GetFileName(uriObj.LocalPath);  
  40.   
  41.             CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(accessKey);  
  42.             CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();  
  43.             string strContainerName = "uploads";  
  44.             CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(strContainerName);  
  45.   
  46.             string pathPrefix = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd") + "/";  
  47.             CloudBlobDirectory blobDirectory = cloudBlobContainer.GetDirectoryReference(pathPrefix);  
  48.             // get block blob refarence    
  49.             CloudBlockBlob blockBlob = blobDirectory.GetBlockBlobReference(BlobName);  
  50.   
  51.             // delete blob from container        
  52.             await blockBlob.DeleteAsync();  
  53.         }  
  54.   
  55.   
  56.         private string GenerateFileName(string fileName)  
  57.         {  
  58.             string strFileName = string.Empty;  
  59.             string[] strName = fileName.Split('.');  
  60.             strFileName = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd") + "/" + DateTime.Now.ToUniversalTime().ToString("yyyyMMdd\\THHmmssfff") + "." + strName[strName.Length - 1];  
  61.             return strFileName;  
  62.         }  
  63.   
  64.         private async Task<string> UploadFileToBlobAsync(string strFileName, byte[] fileData, string fileMimeType)  
  65.         {  
  66.             try  
  67.             {  
  68.                 CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(accessKey);  
  69.                 CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();  
  70.                 string strContainerName = "uploads";  
  71.                 CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(strContainerName);  
  72.                 string fileName = this.GenerateFileName(strFileName);  
  73.   
  74.                 if (await cloudBlobContainer.CreateIfNotExistsAsync())  
  75.                 {  
  76.                     await cloudBlobContainer.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });  
  77.                 }  
  78.   
  79.                 if (fileName != null && fileData != null)  
  80.                 {  
  81.                     CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(fileName);  
  82.                     cloudBlockBlob.Properties.ContentType = fileMimeType;  
  83.                     await cloudBlockBlob.UploadFromByteArrayAsync(fileData, 0, fileData.Length);  
  84.                     return cloudBlockBlob.Uri.AbsoluteUri;  
  85.                 }  
  86.                 return "";  
  87.             }  
  88.             catch (Exception ex)  
  89.             {  
  90.                 throw (ex);  
  91.             }  
  92.         }  
  93.     }  
  94. }  
Step 12
 
Now, go to the data context layer and create the data context layer for storing the file information in the SQL database using the Entity Framework concept.
 
IUnitOfWork.cs
  1. using DataContext;  
  2. using DataContext.Abstractions;  
  3.   
  4. namespace DataContext  
  5. {  
  6.     public interface IUnitOfWork  
  7.     {  
  8.         IProductRepository ProductRepo { get; }  
  9.   
  10.         int SaveChanges();  
  11.     }  
  12. }  
UnitOfWork.cs
  1. using DataContext.Abstractions;  
  2. using DataContext.DataContext;  
  3. using DataContext.Implementation;  
  4. using Microsoft.EntityFrameworkCore;  
  5.   
  6. namespace DataContext  
  7. {  
  8.     public class UnitOfWork : IUnitOfWork  
  9.     {  
  10.         private DbContext db;  
  11.         public UnitOfWork()  
  12.         {  
  13.             db = new EFDBContext();  
  14.         }        
  15.   
  16.         private IProductRepository _ProductRepo;  
  17.         public IProductRepository ProductRepo  
  18.         {  
  19.             get  
  20.             {  
  21.                 if (_ProductRepo == null)  
  22.                     _ProductRepo = new ProductRepository(db);  
  23.   
  24.                 return _ProductRepo;  
  25.             }  
  26.         }  
  27.   
  28.         public int SaveChanges()  
  29.         {  
  30.             return db.SaveChanges();  
  31.         }  
  32.     }  
  33. }  
IRepository.cs
  1. using System.Collections.Generic;  
  2.   
  3. namespace DataContext.Abstractions  
  4. {  
  5.     public interface IRepository<TEntity> where TEntity : class  
  6.     {  
  7.         void Add(TEntity model);  
  8.   
  9.         IEnumerable<TEntity> GetAll();  
  10.   
  11.         TEntity GetById(object Id);  
  12.   
  13.         void Modify(TEntity model);  
  14.   
  15.         void Delete(TEntity model);  
  16.   
  17.         void DeleteById(object Id);  
  18.     }  
  19. }  
Repository.cs
  1. using DataContext.Abstractions;  
  2. using Microsoft.EntityFrameworkCore;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5.   
  6. namespace DataContext.Implementation  
  7. {  
  8.     public class Repository<TEntity> : IRepository<TEntity> where TEntity : class  
  9.     {  
  10.         protected DbContext db { getset; }  
  11.   
  12.         public void Add(TEntity model)  
  13.         {  
  14.             db.Set<TEntity>().Add(model);  
  15.         }  
  16.   
  17.         public void Delete(TEntity model)  
  18.         {  
  19.             db.Set<TEntity>().Remove(model);  
  20.         }  
  21.   
  22.         public void DeleteById(object Id)  
  23.         {  
  24.             TEntity entity = db.Set<TEntity>().Find(Id);  
  25.             this.Delete(entity);  
  26.         }  
  27.   
  28.         public IEnumerable<TEntity> GetAll()  
  29.         {  
  30.             return db.Set<TEntity>().ToList();  
  31.         }  
  32.   
  33.         public TEntity GetById(object Id)  
  34.         {  
  35.             return db.Set<TEntity>().Find(Id);  
  36.         }  
  37.   
  38.         public void Modify(TEntity model)  
  39.         {  
  40.             db.Entry<TEntity>(model).State = EntityState.Modified;  
  41.         }  
  42.     }  
  43. }  
EFDataContext.cs
  1. using DataContext.Models;  
  2. using Microsoft.EntityFrameworkCore;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Text;  
  6.   
  7. namespace DataContext.DataContext  
  8. {  
  9.    public class EFDBContext :DbContext  
  10.     {  
  11.         public EFDBContext()  
  12.         {  
  13.   
  14.         }  
  15.   
  16.         public EFDBContext(DbContextOptions<EFDBContext> options) : base(options)  
  17.         {  
  18.   
  19.         }  
  20.   
  21.         public DbSet<Product> Product { getset; }  
  22.   
  23.         protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
  24.         {  
  25.             if (!optionsBuilder.IsConfigured)  
  26.             {  
  27.                 optionsBuilder.UseSqlServer(@"data source=xxxx; initial catalog=ProjectDB;persist security info=True;user id=sa;password=xxxxxxx;");  
  28.             }  
  29.             base.OnConfiguring(optionsBuilder);  
  30.         }  
  31.     }  
  32. }  
ProductRepository.cs
  1. using DataContext.Abstractions;  
  2. using DataContext.DataContext;  
  3. using DataContext.Models;  
  4. using Microsoft.EntityFrameworkCore;  
  5.   
  6. namespace DataContext.Implementation  
  7. {  
  8.     public class ProductRepository : Repository<Product>, IProductRepository  
  9.     {  
  10.         private EFDBContext context  
  11.         {  
  12.             get  
  13.             {  
  14.                 return db as EFDBContext;  
  15.             }  
  16.         }  
  17.   
  18.         public ProductRepository(DbContext db)  
  19.         {  
  20.             this.db = db;  
  21.         }  
  22.     }  
  23. }  
Step 13
 
Now, go to the main projects; i.e., MVC Application projects.
 
Step 14
 
Select the Controller folder and add a new MVC Controller Name ProductsController.cs
 
Step 15
 
Now, within the controller class, write down the below code within the Index Method.
  1. public IActionResult Index()  
  2.         {  
  3.             return View(_context.ProductRepo.GetAll());  
  4.         }  
Step 16
 
Now, see a new view against the Index method by clicking the right mouse button. A new view has been added in the view folder. Now add the below code in the view file. 
  1. @model DataContext.Models.Product  
  2.   
  3. @{  
  4.     ViewData["Title"] = "Details";  
  5. }  
  6.   
  7. <h2>Details</h2>  
  8.   
  9. <div>  
  10.     <h4>Product</h4>  
  11.     <hr />  
  12.     <dl class="dl-horizontal">  
  13.         <dt>  
  14.             @Html.DisplayNameFor(model => model.Name)  
  15.         </dt>  
  16.         <dd>  
  17.             @Html.DisplayFor(model => model.Name)  
  18.         </dd>  
  19.         <dt>  
  20.             @Html.DisplayNameFor(model => model.UnitPrice)  
  21.         </dt>  
  22.         <dd>  
  23.             @Html.DisplayFor(model => model.UnitPrice)  
  24.         </dd>  
  25.         <dt>  
  26.             @Html.DisplayNameFor(model => model.Description)  
  27.         </dt>  
  28.         <dd>  
  29.             @Html.DisplayFor(model => model.Description)  
  30.         </dd>  
  31.         <dt>  
  32.             @Html.DisplayNameFor(model => model.ImageName)  
  33.         </dt>  
  34.         <dd>  
  35.             @Html.DisplayFor(model => model.ImageName)  
  36.         </dd>  
  37.         <dt>  
  38.             @Html.DisplayNameFor(model => model.ImagePath)  
  39.         </dt>  
  40.         <dd>  
  41.             @Html.DisplayFor(model => model.ImagePath)  
  42.         </dd>  
  43.         <dt>  
  44.             @Html.DisplayNameFor(model => model.CreatedDate)  
  45.         </dt>  
  46.         <dd>  
  47.             @Html.DisplayFor(model => model.CreatedDate)  
  48.         </dd>  
  49.         <dt>  
  50.             @Html.DisplayNameFor(model => model.UpdatedDate)  
  51.         </dt>  
  52.         <dd>  
  53.             @Html.DisplayFor(model => model.UpdatedDate)  
  54.         </dd>  
  55.     </dl>  
  56. </div>  
  57. <div>  
  58.     <a asp-action="Edit" asp-route-id="@Model.ProductId">Edit</a> |  
  59.     <a asp-action="Index">Back to List</a>  
  60. </div>  
Step 17
 
Now, create a new method for creating in the ProductsController and add related view against that action method. 
  1. public IActionResult Create()  
  2.        {  
  3.            return View();  
  4.        }  
Create.cshtml
  1. @model DataContext.Models.Product  
  2.   
  3. @{  
  4.     ViewData["Title"] = "Create";  
  5. }  
  6.   
  7. <h2>Create</h2>  
  8.   
  9. <h4>Product</h4>  
  10. <hr />  
  11. @using (Html.BeginForm("Create""Products", FormMethod.Post, new { enctype = "multipart/form-data" }))  
  12. {  
  13.     @Html.AntiForgeryToken()  
  14.     <div class="form-horizontal">  
  15.         @Html.ValidationSummary(true""new { @class = "text-danger" })          
  16.         <div class="form-group">  
  17.             @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
  18.             <div class="col-md-10">  
  19.                 @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })  
  20.                 @Html.ValidationMessageFor(model => model.Name, ""new { @class = "text-danger" })  
  21.             </div>  
  22.         </div>  
  23.         <div class="form-group">  
  24.             @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })  
  25.             <div class="col-md-10">  
  26.                 @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })  
  27.                 @Html.ValidationMessageFor(model => model.Description, ""new { @class = "text-danger" })  
  28.             </div>  
  29.         </div>  
  30.         <div class="form-group">  
  31.             @Html.LabelFor(model => model.UnitPrice, htmlAttributes: new { @class = "control-label col-md-2" })  
  32.             <div class="col-md-10">  
  33.                 @Html.EditorFor(model => model.UnitPrice, new { htmlAttributes = new { @class = "form-control" } })  
  34.                 @Html.ValidationMessageFor(model => model.UnitPrice, ""new { @class = "text-danger" })  
  35.             </div>  
  36.         </div>  
  37.         <div class="form-group">  
  38.             @Html.LabelFor(model => model.File, htmlAttributes: new { @class = "control-label col-md-2" })  
  39.             <div class="col-md-10">  
  40.                 @Html.TextBoxFor(m => m.File, new { type = "file" })  
  41.                 @Html.ValidationMessageFor(m => m.File)  
  42.             </div>  
  43.         </div>  
  44.         <div class="form-group">  
  45.             <div class="col-md-offset-2 col-md-10">  
  46.                 <input type="submit" value="Create" class="btn btn-default" />  
  47.             </div>  
  48.         </div>  
  49.     </div>  
  50. }  
  51.   
  52. <div>  
  53.     <a asp-action="Index">Back to List</a>  
  54. </div>  
  55.   
  56. @section Scripts {  
  57.     @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}  
  58. }  
Step 18
 
Now, create an action method for saving the data and write down the below code.
  1. [HttpPost]  
  2.         [ValidateAntiForgeryToken]  
  3.         public IActionResult Create(Product product)  
  4.         {  
  5.             if (ModelState.IsValid)  
  6.             {  
  7.  
  8.                 #region Read File Content  
  9.   
  10.                 var uploads = Path.Combine(env.WebRootPath, "uploads");  
  11.                 bool exists = Directory.Exists(uploads);  
  12.                 if (!exists)  
  13.                     Directory.CreateDirectory(uploads);  
  14.   
  15.                 var fileName = Path.GetFileName(product.File.FileName);  
  16.                 var fileStream = new FileStream(Path.Combine(uploads, product.File.FileName), FileMode.Create);  
  17.                 string mimeType = product.File.ContentType;  
  18.                 byte[] fileData = new byte[product.File.Length];  
  19.   
  20.                 BlobStorageService objBlobService = new BlobStorageService();  
  21.   
  22.                 product.ImagePath = objBlobService.UploadFileToBlob(product.File.FileName, fileData, mimeType);  
  23.                 #endregion  
  24.   
  25.                 _context.ProductRepo.Add(product);  
  26.                 _context.SaveChanges();  
  27.                 return RedirectToAction(nameof(Index));  
  28.             }  
  29.             return View(product);  
  30.         }  
Step 19
 
Now, run the application and try to insert a new record from the application.
 
Upload Files In Azure Blob Storage Using ASP.NET Core 
 
Create Mode View.
 
Upload Files In Azure Blob Storage Using ASP.NET Core 
 
Step 20
 
Now, go back to the Azure portal and check if the newly inserted data is shown in the data explorer or not.
 
Upload Files In Azure Blob Storage Using ASP.NET Core 
 
Step 21
 
Similarly, add the edit records and delete records functionality along with the related view. 
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.AspNetCore.Mvc;  
  6. using Microsoft.AspNetCore.Mvc.Rendering;  
  7. using Microsoft.EntityFrameworkCore;  
  8. using DataContext.DataContext;  
  9. using DataContext.Models;  
  10. using System.IO;  
  11. using Microsoft.AspNetCore.Hosting;  
  12. using DataContext;  
  13. using System.Net.Http;  
  14. using ServiceLayer;  
  15. using Microsoft.Extensions.Configuration;  
  16.   
  17. namespace BlobStorage_File_Upload.Controllers  
  18. {  
  19.     public class ProductsController : Controller  
  20.     {  
  21.         private UnitOfWork _context;  
  22.         IHostingEnvironment env;  
  23.         private NumberToWord objNumberToWord;  
  24.   
  25.         public ProductsController(IHostingEnvironment _env)  
  26.         {  
  27.             this._context = new UnitOfWork();  
  28.             env = _env;  
  29.             this.objNumberToWord = new NumberToWord();  
  30.         }  
  31.   
  32.         // GET: Products  
  33.         public IActionResult Index()  
  34.         {  
  35.             return View(_context.ProductRepo.GetAll());  
  36.         }  
  37.   
  38.         // GET: Products/Details/5  
  39.         public IActionResult Details(int? id)  
  40.         {  
  41.             if (id == null)  
  42.             {  
  43.                 return NotFound();  
  44.             }  
  45.   
  46.             var product = _context.ProductRepo.GetById(id);  
  47.             if (product == null)  
  48.             {  
  49.                 return NotFound();  
  50.             }  
  51.   
  52.             return View(product);  
  53.         }  
  54.   
  55.         // GET: Products/Create  
  56.         public IActionResult Create()  
  57.         {  
  58.             return View();  
  59.         }  
  60.          
  61.         [HttpPost]  
  62.         [ValidateAntiForgeryToken]  
  63.         public IActionResult Create(Product product)  
  64.         {  
  65.             if (ModelState.IsValid)  
  66.             {  
  67.  
  68.                 #region Read File Content  
  69.   
  70.                 var uploads = Path.Combine(env.WebRootPath, "uploads");  
  71.                 bool exists = Directory.Exists(uploads);  
  72.                 if (!exists)  
  73.                     Directory.CreateDirectory(uploads);  
  74.   
  75.                 string fileName = Path.GetFileName(product.File.FileName);  
  76.                 byte[] fileData;  
  77.                 using (var target = new MemoryStream())  
  78.                 {  
  79.                     product.File.CopyTo(target);  
  80.                     fileData = target.ToArray();  
  81.                 }  
  82.   
  83.   
  84.                 //var fileStream = new FileStream(Path.Combine(uploads, product.File.FileName), FileMode.Create);  
  85.                 string mimeType = product.File.ContentType;  
  86.                 //= new byte[product.File.Length];  
  87.   
  88.                 BlobStorageService objBlobService = new BlobStorageService();  
  89.   
  90.                 product.ImagePath = objBlobService.UploadFileToBlob(product.File.FileName, fileData, mimeType);  
  91.                 #endregion  
  92.   
  93.                 _context.ProductRepo.Add(product);  
  94.                 _context.SaveChanges();  
  95.                 return RedirectToAction(nameof(Index));  
  96.             }  
  97.             return View(product);  
  98.         }  
  99.   
  100.         // GET: Products/Edit/5  
  101.         public IActionResult Edit(int? id)  
  102.         {  
  103.             if (id == null)  
  104.             {  
  105.                 return NotFound();  
  106.             }  
  107.   
  108.             var product = _context.ProductRepo.GetById(id);  
  109.             if (product == null)  
  110.             {  
  111.                 return NotFound();  
  112.             }  
  113.             return View(product);  
  114.         }  
  115.   
  116.         // POST: Products/Edit/5  
  117.         // To protect from overposting attacks, please enable the specific properties you want to bind to, for   
  118.         // more details see http://go.microsoft.com/fwlink/?LinkId=317598.  
  119.         [HttpPost]  
  120.         [ValidateAntiForgeryToken]  
  121.         public IActionResult Edit(int id, [Bind("ProductId,Name,UnitPrice,Description,ImageName,ImagePath,CreatedDate,UpdatedDate")] Product product)  
  122.         {  
  123.             if (id != product.ProductId)  
  124.             {  
  125.                 return NotFound();  
  126.             }  
  127.   
  128.             if (ModelState.IsValid)  
  129.             {  
  130.                 try  
  131.                 {  
  132.                     _context.ProductRepo.Modify(product);  
  133.                     _context.SaveChanges();  
  134.                 }  
  135.                 catch (DbUpdateConcurrencyException)  
  136.                 {  
  137.                     if (!ProductExists(product.ProductId))  
  138.                     {  
  139.                         return NotFound();  
  140.                     }  
  141.                     else  
  142.                     {  
  143.                         throw;  
  144.                     }  
  145.                 }  
  146.                 return RedirectToAction(nameof(Index));  
  147.             }  
  148.             return View(product);  
  149.         }  
  150.   
  151.         // GET: Products/Delete/5  
  152.         public IActionResult Delete(int? id)  
  153.         {  
  154.             if (id == null)  
  155.             {  
  156.                 return NotFound();  
  157.             }  
  158.   
  159.             var product = _context.ProductRepo.GetById(id);  
  160.             if (product == null)  
  161.             {  
  162.                 return NotFound();  
  163.             }  
  164.   
  165.             return View(product);  
  166.         }  
  167.   
  168.         // POST: Products/Delete/5  
  169.         [HttpPost, ActionName("Delete")]  
  170.         [ValidateAntiForgeryToken]  
  171.         public IActionResult DeleteConfirmed(int id)  
  172.         {  
  173.             var product = _context.ProductRepo.GetById(id);  
  174.             BlobStorageService objBlob = new BlobStorageService();  
  175.             objBlob.DeleteBlobData(product.ImagePath);  
  176.             _context.ProductRepo.Delete(product);  
  177.             _context.SaveChanges();  
  178.             return RedirectToAction(nameof(Index));  
  179.         }  
  180.   
  181.         private bool ProductExists(int id)  
  182.         {  
  183.             return _context.ProductRepo.GetAll().Any(e => e.ProductId == id);  
  184.         }  
  185.     }  
  186. }  
Step 22
 
Now run the application and create new products with the help of Product UI. 
 
 
 
 
 

Conclusion

 
Now, in this article, we discussed how to insert, update, or delete file DB Database in Azure portal using ASP.NET Core. I hope this article will help you understand. In the next article, we will discuss how to upload files in Azure Blob Storage. For any further query or clarification, ping me.