This article will explain the communication between Web API(.NET 7) and Azure Blob Storage for managing files.
Storage Account:
(Step 3):
Fill out the 'Create A Storage Account' form.
In the 'appsettings.Development.json' let's add the connection string.
Azure Blob Storage:
Azure Blob Storage is a Microsoft Cloud Storage. Azure Blob Storage is used to manage the files for storing or reading.
A Storage account gives us a unique namespace. Every file we save or store on Azure Storage must have an address, and that address is nothing but the unique name of our Storage Account name. The combination of the storage account name and Azure blob Storage endpoint forms the base address. For example, if our storage account is named as 'my-azure-account' then the base address will be like 'https://my-azure-account.blob.core.window.net'.
Containers:
The Containers are just like folders.
Blob:
The actual item or file we will store inside of the container.
Create Azure Blob Storage In Azure Portal:
(Step 1)First, we have to 'Sing-Up' in 'Microsoft Azure Portal', after completing 'Sing-Up' and then 'Sing-In' portal we can observe an azure portal like below. And then click on the 'Create A Resource' button.
(Step 2) Search like 'Storage Account' and then click on the 'Create' button.
Fill out the 'Create A Storage Account' form.
- Here in the 'Subscription' field make sure to select your subscription which may be paid or free. If you use paid subscription also the Microsoft won't charge for basic usage so it will be a benefit for those who are newly working with Azure Blob Storage.
- Here the 'Resource Group' is like a folder which holds the azure services in our case Azure Blob Storage Service going to be stored in the defined 'Resource Group' name
- Here 'Storage Account Name' field, here give a meaning full name because this name will be used to generate the subdomain URL for our Azure Blob Storage.
- Here 'Region' you can leave the default or you choose the nearest location to host your server
- Here 'Performance' & 'Redundancy' to default values.
Now Click on the 'Review. button at the bottom, so that we can directly navigate to the 'Review' tab because all the remaining tabs can be skipped with default values. Now on the 'Review' tab click on the 'Create' button at the bottom
(Step 5)Now click on the 'Go to resource' button
(Step 6):Now in our Azure Blob Storage account, go to the 'Container' left side menu item, then click on '+ Container' button. Then in the create container form give your container name and in the 'Public Access Level' drops down give a value like 'Container(anonymous read access for containers)'. Finally, click on the create button.
(Step 7):We can observe our newly created container below.
Create A .NET 7 Web API Application:
Let's create the .NET 7 Web API application to implement our demo on Azure Blob Storage. The most recommended IDEs are Visual Studio 2022(V17.4.* supports .NET 7) or Visual Studio Code. In this demo, I'm using the Visual Studio Code editor.
dotnet new webapi -o name_of_your_project
Install Azure Blob Storage Package:
Let's install the Azure Blob Storage package.
.NET CLI Command
dotnet add package Azure.Storage.Blobs --version 12.14.1
dotnet add package Azure.Storage.Blobs --version 12.14.1
Package Manager Command
NuGet\Install-Package Azure.Storage.Blobs -Version 12.14.1
NuGet\Install-Package Azure.Storage.Blobs -Version 12.14.1
Add Azure Storage ConnectionString:
Go to our Azure Storage Account, then go to the 'Security + Network' menu on the left-hand side menu, then click on the 'Access Keys' then we can see 'Key1' & 'Key2' connection strings any one can be used into our API.
appsettings.Development.json:
"ConnectionStrings": { "AzureStorage":"your azure storage connection string value" }
Register 'BlobServiceClient':
In the 'Program.cs' file register the 'Azure.Storage.Blob.BlobServiceClient'.
Program.cs:
using Azure.Storage.Blobs; builder.Services.AddScoped(_ => { return new BlobServiceClient(builder.Configuration.GetConnectionString("AzureStorage")); });
- Here for the 'BlobServiceClient' instance pass our connection string value as an input parameter.
Create A Service Like 'FileService':
To implement our core logic let's create the service files like 'IFileService.cs' & 'FileService.cs' in the 'Services' folder(new folder).
Services/IFileService.cs:
namespace dot7.blob.demo.Services; public interface IFileService { }Services/FileService.cs:
using Azure.Storage.Blobs; namespace dot7.blob.demo.Services; public class FileService: IFileService { private readonly BlobServiceClient _blobServiceClient; public FileService(BlobServiceClient blobServiceClient) { _blobServiceClient = blobServiceClient; } }
- Here injected the 'Azure.Storage.Blobs.BlobServiceClient'.
Program.cs:
builder.Services.AddScoped<IFileService, FileService>();
Create A API Controller Like 'FileController':
Let's create a new API controller like 'FileController'.
Controllers/FileController.cs:
using dot7.blob.demo.Services; using Microsoft.AspNetCore.Mvc; namespace dot7.blob.demo.Controllers; [ApiController] [Route("[controller]")] public class FileController: ControllerBase { private readonly IFileService _fileService; public FileController(IFileService fileService) { _fileService = fileService; } }
- Here injected our 'IFileService'.
Create File Upload Endpoint:
Let's create a payload model for our file upload like 'FileModel.cs' in the 'Models' folder.
Models/FileModel.cs:
namespace dot7.blob.demo.Models; public class FileModel { public IFormFile ImageFile { get; set; } }
- The 'Microsoft.AspNetCore.Http.IFormFile' type can read a stream of the file from the form data.
Let's add the logic for uploading the file to our Azure Blob Storage in our 'FileService'.
Services/IFileService.cs:
Task Upload(FileModel fileModel);Services/FileService.cs:
public async Task Upload(FileModel fileModel) { var blobContainer = _blobServiceClient.GetBlobContainerClient("mycontainer"); var blobClient = blobContainer.GetBlobClient(fileModel.ImageFile.FileName); await blobClient.UploadAsync(fileModel.ImageFile.OpenReadStream()); }
- (Line: 3) Create an instance for our azure blob container. Here we have to pass our container name to the 'GetBlobContainerClient' method.
- (Line: 5) Create the instance of the blob with the name, so this blob instance(any file) we are going to upload to our Azure cloud.
- (Line: 7) Here 'UploadAsync' method saves our file to the Azure Cloud.
Controllers/FileController.cs:
[Route("upload")] [HttpPost] public async Task<IActionResult> Upload([FromForm]FileModel model) { if (model.ImageFile != null) { await _fileService.Upload(model); } return Ok(); }
Add File Read Endpoint:
Let's implement the logic for reading the file from Azure Blob Storage.
Services/IFileService.cs:
Task<Stream> Get(string imageName);Services/FileService.cs:
public async Task<Stream> Get(string imageName) { var blobContainer = _blobServiceClient.GetBlobContainerClient("mycontainer"); var blobClient = blobContainer.GetBlobClient(imageName); var downloadContent = await blobClient.DownloadAsync(); return downloadContent.Value.Content; }
- (Line: 3) Create the container instance by using our Azure Blob Storage container name.
- (Line: 5) Crate the blob instance from the container instance.
- (Line: 6&7) Download the stream of the blob(file).
Controllers/FileController.cs:
[Route("get")] [HttpGet] public async Task<IActionResult> Get(string fileName) { var imgStream = await _fileService.Get(fileName); string fileType = "jpeg"; if (fileName.Contains("png")) { fileType = "png"; } return File(imgStream, $"image/{fileType}"); }
- (Line: 11) Using the 'File' method we return our blob stream as a response.
Add File Download Endpoint:
Let's add the file download endpoint as below.
Controllers/FileController.cs:
[Route("download")] [HttpGet] public async Task<IActionResult> GetDownload(string fileName) { var imgStream = await _fileService.Get(fileName); string fileType = "jpeg"; if (fileName.Contains("png")) { fileType = "png"; } return File(imgStream, $"image/{fileType}",$"blobfile.{fileType}"); }
- Here download endpoint is almost similar to our read endpoint only change we used the overloaded 'File' method that takes the name of the file to download.
Support Me!
Buy Me A Coffee
PayPal Me
video Session:
Wrapping Up:
Hopefully, I think this article delivered some useful information of approaches to consuming Azure Blob Storage in .Net7 Web API. I love to have your feedback, suggestions, and better techniques in the comment section below.
I can't see your third YouTube video is private
ReplyDeleteHow can you return the % progress from the blobclient.UploadAsync?
ReplyDelete