Code2night
  • Home
  • Blogs
  • Tutorial
  • Post Blog
  • Tools
    • Json Beautifier
    • Html Beautifier
  • Members
    • Register
    • Login
  1. Home
  2. Blogpost
26 Feb
2023

How to use Azure Blob Storage in an ASP.NET Core Web API to list, upload, download, and delete files

by Shubham Batra

310

Download Attachment

Create a new Azure Storage Account

Open up the Azure Portal and search for Storage Accounts and open that page. You will now be able to create a new storage account, by using the “Create”

Create a Blob Container at the Storage Account

Click on the Storage Account and select Container in the menu on your left side.

Create a new ASP.NET Web API to handle files in Azure

Open Visual Studio and create a new project with the ASP.NET Core Web API template and.NET 6 (Long-term Support) as the framework. I have not placed my solution and project in the same folder. Optionally, you can enable Docker support if you are thinking of containerizing the solution.

Install required NuGet Packages

Azure.Storage.Blobs

Install-Package Azure.Storage.Blobs 

Microsoft.VisualStudio.Azure.Containers.Tools.Targets

Install-Package Microsoft.VisualStudio.Azure.Containers.Tools.Targets

Add configuration details to appsettings.json
Open appsettings.json and add the following lines below "AllowedHosts":

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "BlobConnectionString": "Your Connection string from Azure",
  "BlobContainerName": "Your container name in Azure"
}

Create a new folder named "Models," a new public class named "BlobDto," and another one named "BlobResponseDto."

Place the below code inside BlobDto.cs.

namespace AzureBlobStorage.Models
{
    public class BlobDto
    {
        public string? Uri { get; set; }
        public string? Name { get; set; }
        public string? ContentType { get; set; }
        public Stream? Content { get; set; }
    }
}

This is for BlobResponseDto.cs

namespace AzureBlobStorage.Models
{
    public class BlobResponseDto
    {
        public string? Status { get; set; }
        public bool Error { get; set; }
        public BlobDto Blob { get; set; }

        public BlobResponseDto()
        {
            Blob = new BlobDto();
        }
    }
}

Make an Azure Blob Storage repository.

To make it all a bit more clear and easy to maintain in the future or to implement for you in another solution or project, let’s put it all inside a repository and wire that up to a controller using an interface.

Create a new folder named "Services." This will contain our interface for the repository implementation. Create a new public interface and name it IAzureStorage. Place the below code inside the interface:


using AzureBlobStorage.Models;

namespace AzureBlobStorage.Services
{
    public interface IAzureStorage
    {
        /// <summary>
        /// This method uploads a file submitted with the request
        /// </summary>
        /// <param name="file">File for upload</param>
        /// <returns>Blob with status</returns>
        Task<BlobResponseDto> UploadAsync(IFormFile file);

        /// <summary>
        /// This method downloads a file with the specified filename
        /// </summary>
        /// <param name="blobFilename">Filename</param>
        /// <returns>Blob</returns>
        Task<BlobDto> DownloadAsync(string blobFilename);

        /// <summary>
        /// This method deleted a file with the specified filename
        /// </summary>
        /// <param name="blobFilename">Filename</param>
        /// <returns>Blob with status</returns>
        Task<BlobResponseDto> DeleteAsync(string blobFilename);

        /// <summary>
        /// This method returns a list of all files located in the container
        /// </summary>
        /// <returns>Blobs in a list</returns>
        Task<List<BlobDto>> ListAsync();
    }
}

As you can see, we now have four different async methods that make up a CRUD (create, read, update, and delete) interface for files located at Azure. Next, we have to add a new folder named "Repository" and create a new file inside that folder named "AzureStorage.cs."


using Azure.Storage.Blobs.Models;
using Azure.Storage.Blobs;
using AzureBlobStorage.Models;
using AzureBlobStorage.Services;
using Azure;

namespace AzureBlobStorage.Repository
{
    public class AzureStorage : IAzureStorage
    {
        #region Dependency Injection / Constructor

        private readonly string _storageConnectionString;
        private readonly string _storageContainerName;
        private readonly ILogger<AzureStorage> _logger;

        public AzureStorage(IConfiguration configuration, ILogger<AzureStorage> logger)
        {
            _storageConnectionString = configuration.GetValue<string>("BlobConnectionString");
            _storageContainerName = configuration.GetValue<string>("BlobContainerName");
            _logger = logger;
        }

        public async Task<BlobResponseDto> DeleteAsync(string blobFilename)
        {
            BlobContainerClient client = new BlobContainerClient(_storageConnectionString, _storageContainerName);

            BlobClient file = client.GetBlobClient(blobFilename);

            try
            {
                // Delete the file
                await file.DeleteAsync();
            }
            catch (RequestFailedException ex)
                when (ex.ErrorCode == BlobErrorCode.BlobNotFound)
            {
                // File did not exist, log to console and return new response to requesting method
                _logger.LogError($"File {blobFilename} was not found.");
                return new BlobResponseDto { Error = true, Status = $"File with name {blobFilename} not found." };
            }

            // Return a new BlobResponseDto to the requesting method
            return new BlobResponseDto { Error = false, Status = $"File: {blobFilename} has been successfully deleted." };

        }

        public async Task<BlobDto> DownloadAsync(string blobFilename)
        {
            // Get a reference to a container named in appsettings.json
            BlobContainerClient client = new BlobContainerClient(_storageConnectionString, _storageContainerName);

            try
            {
                // Get a reference to the blob uploaded earlier from the API in the container from configuration settings
                BlobClient file = client.GetBlobClient(blobFilename);

                // Check if the file exists in the container
                if (await file.ExistsAsync())
                {
                    var data = await file.OpenReadAsync();
                    Stream blobContent = data;

                    // Download the file details async
                    var content = await file.DownloadContentAsync();

                    // Add data to variables in order to return a BlobDto
                    string name = blobFilename;
                    string contentType = content.Value.Details.ContentType;

                    // Create new BlobDto with blob data from variables
                    return new BlobDto { Content = blobContent, Name = name, ContentType = contentType };
                }
            }
            catch (RequestFailedException ex)
                when (ex.ErrorCode == BlobErrorCode.BlobNotFound)
            {
                // Log error to console
                _logger.LogError($"File {blobFilename} was not found.");
            }

            // File does not exist, return null and handle that in requesting method
            return null;
        }

        public async Task<List<BlobDto>> ListAsync()
        {
            // Get a reference to a container named in appsettings.json
            BlobContainerClient container = new BlobContainerClient(_storageConnectionString, _storageContainerName);

            // Create a new list object for 
            List<BlobDto> files = new List<BlobDto>();

            await foreach (BlobItem file in container.GetBlobsAsync())
            {
                // Add each file retrieved from the storage container to the files list by creating a BlobDto object
                string uri = container.Uri.ToString();
                var name = file.Name;
                var fullUri = $"{uri}/{name}";

                files.Add(new BlobDto
                {
                    Uri = fullUri,
                    Name = name,
                    ContentType = file.Properties.ContentType
                });
            }

            // Return all files to the requesting method
            return files;
        }

        public async Task<BlobResponseDto> UploadAsync(IFormFile blob)
        {
            // Create new upload response object that we can return to the requesting method
            BlobResponseDto response = new();

            // Get a reference to a container named in appsettings.json and then create it
            BlobContainerClient container = new BlobContainerClient(_storageConnectionString, _storageContainerName);
            //await container.CreateAsync();
            try
            {
                // Get a reference to the blob just uploaded from the API in a container from configuration settings
                BlobClient client = container.GetBlobClient(blob.FileName);

                // Open a stream for the file we want to upload
                await using (Stream? data = blob.OpenReadStream())
                {
                    // Upload the file async
                    await client.UploadAsync(data);
                }

                // Everything is OK and file got uploaded
                response.Status = $"File {blob.FileName} Uploaded Successfully";
                response.Error = false;
                response.Blob.Uri = client.Uri.AbsoluteUri;
                response.Blob.Name = client.Name;

            }
            // If the file already exists, we catch the exception and do not upload it
            catch (RequestFailedException ex)
               when (ex.ErrorCode == BlobErrorCode.BlobAlreadyExists)
            {
                _logger.LogError($"File with name {blob.FileName} already exists in container. Set another name to store the file in the container: '{_storageContainerName}.'");
                response.Status = $"File with name {blob.FileName} already exists. Please use another name to store your file.";
                response.Error = true;
                return response;
            }
            // If we get an unexpected error, we catch it here and return the error message
            catch (RequestFailedException ex)
            {
                // Log error to console and create a new response we can return to the requesting method
                _logger.LogError($"Unhandled Exception. ID: {ex.StackTrace} - Message: {ex.Message}");
                response.Status = $"Unexpected error: {ex.StackTrace}. Check log with StackTrace ID.";
                response.Error = true;
                return response;
            }

            // Return the BlobUploadResponse object
            return response;
        }

        #endregion

    }
}

Modify Program.cs to use Serilog and register our Azure service.

I have totally rewritten the program. CS file because I wanted to add some extra logging. I have decided to add Serilog and write it to the console.

Install serilog Packages 

using AzureBlobStorage.Common;
using AzureBlobStorage.Repository;
using AzureBlobStorage.Services;
using Serilog;

StaticLogger.EnsureInitialized();
Log.Information("Azure Storage API Booting Up...");

try
{
    var builder = WebApplication.CreateBuilder(args);

    // Add Serilog
    builder.Host.UseSerilog((_, config) =>
    {
        config.WriteTo.Console();
        //.ReadFrom.Configuration(builder.Configuration);
    });

    builder.Services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));



    builder.Services.AddControllers();
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();

    // Add Azure Repository Service
    builder.Services.AddTransient<IAzureStorage, AzureStorage>();
    Log.Information("Services has been successfully added...");

    var app = builder.Build();

    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }

    app.UseHttpsRedirection();

    app.UseAuthorization();

    app.MapControllers();

    app.Run();
    Log.Information("API is now ready to serve files to and from Azure Cloud Storage...");
}
catch (Exception ex) when (!ex.GetType().Name.Equals("StopTheHostException", StringComparison.Ordinal))
{
    StaticLogger.EnsureInitialized();
    Log.Fatal(ex, "Unhandled Exception");
}
finally
{
    StaticLogger.EnsureInitialized();
    Log.Information("Azure Storage API Shutting Down...");
    Log.CloseAndFlush();
}

As you might notice, I use a class named StaticLogger with the method EnsureInitialized(). For you to get that, you have to add a new folder named Common and then add a new class named StaticLogger.cs. Below is the implementation for StaticLogger.cs.

using Serilog;

namespace AzureBlobStorage.Common
{
    public class StaticLogger
    {
        public static void EnsureInitialized()
        {
            if (Log.Logger is not Serilog.Core.Logger)
            {
                Log.Logger = new LoggerConfiguration()
                    .Enrich.FromLogContext()
                    .WriteTo.Console()
                    .CreateLogger();
            }
        }
    }
}

Create a StorageController for implementing Azure Blob Storage endpoints.

The controller is a simple one with four actions. Each action is returning an IActionResult when the repository has done its work against our Azure Blob Storage.

I have not created any names for the routes, as the four methods are different. If you want, you can change the names of the routes. In a production environment, I would most likely change this to include naming, especially if I have multiple actions in the same controller that use the same request methods (POST, GET, DELETE, PUT). 

using AzureBlobStorage.Models;
using AzureBlobStorage.Services;
using Microsoft.AspNetCore.Mvc;

namespace AzureBlobStorage.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class StorageController : ControllerBase
    {
        private readonly IAzureStorage _storage;

        public StorageController(IAzureStorage storage)
        {
            _storage = storage;
        }

        [HttpGet(nameof(Get))]
        public async Task<IActionResult> Get()
        {
            // Get all files at the Azure Storage Location and return them
            List<BlobDto>? files = await _storage.ListAsync();

            // Returns an empty array if no files are present at the storage container
            return StatusCode(StatusCodes.Status200OK, files);
        }

        [HttpPost(nameof(Upload))]
        public async Task<IActionResult> Upload(IFormFile file)
        {
            BlobResponseDto? response = await _storage.UploadAsync(file);

            // Check if we got an error
            if (response.Error == true)
            {
                // We got an error during upload, return an error with details to the client
                return StatusCode(StatusCodes.Status500InternalServerError, response.Status);
            }
            else
            {
                // Return a success message to the client about successfull upload
                return StatusCode(StatusCodes.Status200OK, response);
            }
        }

        [HttpGet("{filename}")]
        public async Task<IActionResult> Download(string filename)
        {
            BlobDto? file = await _storage.DownloadAsync(filename);

            // Check if file was found
            if (file == null)
            {
                // Was not, return error message to client
                return StatusCode(StatusCodes.Status500InternalServerError, $"File {filename} could not be downloaded.");
            }
            else
            {
                // File was found, return it to client
                return File(file.Content, file.ContentType, file.Name);
            }
        }

        [HttpDelete("filename")]
        public async Task<IActionResult> Delete(string filename)
        {
            BlobResponseDto response = await _storage.DeleteAsync(filename);

            // Check if we got an error
            if (response.Error == true)
            {
                // Return an error message to the client
                return StatusCode(StatusCodes.Status500InternalServerError, response.Status);
            }
            else
            {
                // File has been successfully deleted
                return StatusCode(StatusCodes.Status200OK, response.Status);
            }
        }
    }
}




  • |
  • Azure Blob Storage in an ASPNET Core

Comments

Follow Us On Social Media - Like Us On Facebook

Tags

LinkedinLogin
LinkedinProfile
GetLinkedinProfile
C#
Aspnet
MVC
Linkedin
ITextSharp
Export to Pdf
AspNet Core
AspNet
View to Pdf in Aspnet
Model Validation In ASPNET Core MVC 60
Model Validation
Model Validation In ASPNET Core MVC
Model Validation In ASPNET
Image Compression in AspNet
Compress Image in c#
AspNet MVC
Image Optimize in C#
Scheduler
Web Api in Aspnet MVC
Web API CRUD Operations
Web API CRUD Operations In ASPNET MVC Application
create a read only MySQL user
Scheduler Service
Task scheduler in AspNet
Task Scheduler
Git Tutorial for Beginners and Intermediate
Git Tutorial
Git
Github
commit
repository
push
pull request
branches
Git Branching and Merging
Branching
Merging
compress images csharp
compress jpeg csharp
compress png csharp
compress tiff csharp
Slick Slider
Slick Slider Responsive
Csharp
OpenJson
Sql server
Json
Numbers validation javascript
Allow only numbers to be typed in a textbox
Number validation in JavaScript
Numric only validation in javascript
Alphanumeric validation javascript
Allow only Alphanumeric to be typed in a textbox
Alphanumeric validation in JavaScript
Number And Decimal validation javascript
Allow only Number And Decimal to be typed in a textbox
Number And Decimal validation in JavaScriptA
Alphabets validation javascript
Allow only Alphabets to be typed in a textbox
Alphabets validation in JavaScript
Aphabet validations using js
Jquery
Validations
AspNet Core MVC Publish using FTP (File Transfer Protocol)
AspNet MVC Publish using FTP (File Transfer Protocol)
AspNet MVC Publish using FTP
AspNet Core MVC Publish using FTP
Publish using FTP
How to add whatsapp share button on a website
How to add a WhatsApp share button on a website
apiwhatsappcom
Share to whatsapp
HTTP Error 50031 Failed to load ASP NET Core runtime
Http Error
The Extender Provider failed to return an Extender for this object
Twilio SMS and ASPNET Core 60
How to Send an SMS with ASPNET Core
Using Dependency Injection with Twilio SMS and ASPNET Core 21
Twillio
Twillio in AspNet
Twillio SMS Integration
Number And Decimal validation in JavaScript
Quickblox
Quickblox javascript sdk
javascript sdk
Audio and video call using js
Quickblox audio call
Quickblox video call
Winforms
DevExpress
Net
Reading Values From Appsettingsjson In ASPNET Core 31 and 60
appsettingsjson
ASPNET Core
Reading Values From appsettingsjson
countdown timer
Timer in js
Jquery InputMask
Input masking
Masking using jquery
Phone mask
Email mask
Input mask using jquery
Firebase
Firebase Database
Firesharp
Firebase using Aspnet
Neo4J
Neo4j Driver
Neo4J in Aspnet
Graph Database
JWT
JWT Token
JWT in AspNet
JWT in Aspnet MVC
Validate jwt token
Twilio SMS And ASPNET MVC
How To Send An SMS With ASPNET MVC
Twillio In AspNet
Implementation Of SignalR With NET Core
Build Real time Applications with ASPNET Core SignalR
NET Core
SignalR
SignalR With NET Core
signalr in aspnet core
Owin Authentication
Owin
Microsoft Owin
Owin in Api
Owin authentication in Api
Twillio Logs
Get Twillio Logs
Paypal
Paypal Integration in AspNet MVC
Paypal Integration
Unable to connect to any of the specified MySQL hosts
Aspnet Core
Paypal in Aspnet core
Payout in Paypal
Paypal Payment Gateway
Payouts
Hangfire with ASPNET Core
Hangfire in ASPNET Core 31
Hangfire in ASPNET
Hangfire
Web Api
Api
Aspnet core
AutoMapper
Automapper in Aspnet MVC
Angular Material Select Dropdown with Image
StreamReader
Json to C#
JWT Token Authentication And Authorizations In Web API
C# Collections
Collections (C#)
Fibonacci series in Java
Display Fibonacci Series
First C# Program
What is C?
C
C Programming
Narrowing Casting
Widening Casting
Java Type Casting
How to Connect to a Database with MySQL Workbench
read only MySQL user
GROUP_CONCAT()
Multiple rows to one comma separated value in Sql Server
Converting commas or other delimiters to a Table or List in SQL Server
Sql Server
Finding table references
T Sql
Finding tables by column name
Renaming column in Sql
RazorPay in Aspnet MVC
RazorPay in net
RazorPay in MVC
RazorPay Integration in AspNet
Implementing RazorPay in Aspnet
aspnetmvc
Ninject In ASPNET MVC
csharp
designpattern
ef
Python
OpenCV
Face Detection
Realtime face detection
AI
fixed header and scrollable body
Simple Pagination
Pagination in mvc
Pagination in Aspnet MVC
MVC Paging
HttpClient
Web Api from Server Side
Calling web api
Consuming web api
Azure Blob Storage in an ASPNET Core
How to upload files to Azure Blob Storage in an ASPNET Core Web
How to delete files to Azure Blob Storage in an ASPNET Core Web
Record HTML Element In aspnet MVC using Jquery
Screen Recording with Audio using JavaScript in ASPNET MVC
Screen recording
How to set Date and time format in IIS Manager
IIS Manager
IIS
Internet Information Services (IIS) Manager
Internet Information Services (IIS)
Internet Information Services
Error Handling In AspNet Core
Exception Handling Asp Net Core
Exception Handling
Exception Handling Asp Net
Creating Log Files in MVC
Error Handling in MVC
Exception Handling in AspNet
Handling Exceptions and Creating Error Logs in Asp net Mvc using base controller
net
Code2Tonight
Stopping Browser Reload On Save
Repository Pattern with ADONet in MVC
Repository Pattern With ASPNET MVC And AdoNet
MVC Crud Operation
Jquery Full Calender Integrated With ASPNET
Full Calendar
Jquery Calendar
Slick Slider Example
responsive carousels
Entity Framework
Intergrate SummerNote Text Editor into AspNet MVC
Web Config
Auto Redirection
Redirection from Http to https
Url Rewriting
Implement Stripe Payment Gateway In ASPNET Core
Stripe Payment Gateway
StripeNet
Convert HTML String To Image In C#
HTMLtoImage
Convert Html to Image in AspNet
Postgre
PgAdmin4
PostgreSql
A Non Fatal Error Occured During Cluster Initialisation In Postgre SQL
Microsoft Outlook
Outlook Appointments
Microsoft Exchange Service
Send Email With HTML Template And PDF Using ASPNet C#
Send Email
Email with html template
email with pdf attachment
email with html and pdf
Microsoft Outlook Contacts
Outlook
Microsoft Exhchange Service
JSON
Convert string with dot notation to JSON
HTTP Error 5025 ANCM Out Of Process Startup Failure
Internet Information Service
Net core
Payumoney Integration With AspNet MVC
Prism js
Highlighting Syntax
Syntax Highlighting
code stylings
c#
Jquery AJax
Ajax
Implement Stripe Payment Gateway In ASPNET
Using Checkout in an ASPNET Web Forms application
Stripe Payment
Stripe Payment Integration
Stripe Integeration
How to upload Image file using AJAX andjQuery
upload Image file using AJAX and jquery
Ajax call
file upload using ajax
file uploading using ajax and jquery
ConfigurationBuilder does not contain a definition for SetBasePath
Reading app json file in dot net core
Appsetting jso
Dot Net Core
Globalization and localization in ASPNET Core
Asp Net Core with Resource file resx
How to get the resx file strings in asp net core
Culture in Net core
Localisation in AspNet Core
Url Encryption in AspNet MVC
Url Encryption in C#
Url Encryption
Custom Helpers
Caching in ASPNET Core using Redis Cache
Redis Cache
Caching in ASPNET Core
ASPNET Core Redis Cache
Slick Slider with single slide
Slick
Vue js
Child Components
How to reload vue js child components
Net Core
Visual Studio
Net core 31
Razor
Zoom sdk
Zoom c# wrapper Inegration
zoom Integration in c#
Zoom Integration
Zoom window sdk
vue js toggle button
vue js
toggle buttons
vuejs
vue js toggle switch
VueJs
SignalR in Net Core
Chat App in Vue js
Chat App using SignalR
AspNet Chat app
JPlayer
Html5 Audio Video Player
Music Player
QR Code Generator
QR Code
Jquery QR Code
Google Maps
Google map api
Places API
Google map Places API in AspNet
Jquery Autocomplete
Autocomplete
Jquery UI Autocomplete
ExcelDataReader
Import data from excel in AspNet
Card Number Formatting
Amex Card Format
Card Format
FCM
Cloud Messaging
Android Notifications
FCM Notifications for IOS
IOS Notifications
Angular js
apply css on child components in Angular js
Angular Mentions
Google Sign In
Google Login
Google Oauth Api
Social Login
Aspnet Mvc
Google + Api
Create and publish a package using Visual Studio (NET Framework
Windows)
Create and publish a nuget package
create your own nuget package
Image compress
Image optimization
compress Image
optimize Image
WebForm
AspNet Web Pages
Batch Script
Database backup
Powershell
ASpNet
Sql Server Backup
AspNet core 31
Aspnet core 21
HttpCookies in AspNet Core
Custom FIlter attribute
Custom Authentication
LinkedIn Authentication
Login using LinkedIN
Social Login in AspNet
LinkedIn Authentication in AspNet MVC
LinkedIn Login in aspnet MVC
Shuffle List in c#
C#Net
Google Login in AspNet MVC
GoogleAuthentication Nuget package
Password Encryption
RFC Encryption
Encryption and Decryption
Encryption in AspNet
Base 64 Encryption
Base 64 Decryption
Swagger UI
Swashbuckle
SwashbuckleAspNetCore
Rest API
Postman
Api Testing
SSRS
SSRS Report
ASPNET MVC
ASPNET MVC SSRS Report
ssrs report
XlWorkbook
ClosedXml
Excel Export
Blazor
Syncfusion
SFGrid
Syncfusion SFgrid
Net core 60
DataTable to List
Extension Methods
Microsoft Access Database Engine
Ace Ole Db 120
MicrosoftACEOLEDB120
OLE DB
Aspnet MVC
Ace OLE DB
rdlc
Report Viewer
RDLC Report
Max Request Length
Thank you for Downloading....!

Subscribe for more tutorials

Support our team

Continue with Downloading

Welcome To Code2night, A common place for sharing your programming knowledge,Blogs and Videos

  • Kurukshetra
  • info@Code2night.com

Links

  • Home
  • Blogs
  • Tutorial
  • Post Blog

Popular Tags

Copyright © 2023 by Code2night. All Rights Reserved

  • Home
  • Blog
  • Login
  • SignUp
  • Contact
  • Privacy Policy
  • Json Beautifier