Azure Blob storage is Microsoft’s object storage solution for the cloud. Blob storage is optimized for storing massive amounts of unstructured data. Unstructured data is data that doesn’t adhere to a particular data model or definition, such as text or binary data.
Blob storage is designed for:
- Serving images or documents directly to a browser.
- Storing files for distributed access.
- Streaming video and audio.
- Writing to log files.
- Storing data for backup and restore, disaster recovery, and archiving.
- Storing data for analysis by an on-premises or Azure-hosted service.
Azure Blob Storage with .NET 6 Web API
Step 1: Create a new .NET Core API Project Open your preferred IDE (such as Visual Studio or Visual Studio Code) and create a new .NET Core API project.
Step 2: Install required packages In your project, you’ll need to install the following NuGet packages:
dotnet add package Azure.Storage.Blobs
Step 3: Create a service to handle Azure Blob Storage operations. In this example, we’ll create an interface and a corresponding implementation:
using Azure.Storage.Blobs; using AzureBlobStroage.Repository.Interfaces; namespace AzureBlobStroage.Repository.Services { public class BlobStorageService:IBlobStorageService { private readonly BlobServiceClient _blobServiceClient; public BlobStorageService(string connectionString) { _blobServiceClient = new BlobServiceClient(connectionString); } public async Task UploadBlobAsync(string containerName, string blobName, Stream content) { var containerClient = _blobServiceClient.GetBlobContainerClient(containerName); await containerClient.UploadBlobAsync(blobName, content); } } }
namespace AzureBlobStroage.Repository.Interfaces { public interface IBlobStorageService { Task UploadBlobAsync(string containerName, string blobName, Stream content); } }
Step 4: Configure the Azure Blob Storage connection string in your appsettings.json
file:
{ "ConnectionStrings": { "BlobStorageConnection": "your-connection-string-here" } }
Step 5: Register the IBlobStorageService
in the Program.cs
file:
using Azure.Storage.Blobs; using AzureBlobStroage.Repository.Interfaces; using AzureBlobStroage.Repository.Services; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; internal class Program { private static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var connectionString = builder.Configuration.GetConnectionString("BlobStorageConnection"); builder.Services.AddSingleton<IBlobStorageService>(new BlobStorageService(connectionString)); builder.Services.AddScoped(x => { var blobConnection = builder.Configuration.GetConnectionString("BlobStorageConnection"); return new BlobServiceClient(blobConnection); }); 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(); } }
Step 6: Create an API controller that uses the IBlobStorageService
to upload a blob, list of uploaded files and also API to download uploaded files:
using Azure.Storage.Blobs; using AzureBlobStroage.Repository.Interfaces; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace AzureBlobStroage.Controllers { [Route("api/[controller]")] [ApiController] public class BlobController : ControllerBase { private readonly IBlobStorageService _blobStorageService; private readonly BlobServiceClient _blobServiceClient; public BlobController(IBlobStorageService blobStorageService, BlobServiceClient blobServiceClient) { _blobStorageService = blobStorageService; _blobServiceClient = blobServiceClient; } [HttpPost] public async Task<IActionResult> UploadBlob([FromForm] IFormFile file) { if (file == null || file.Length == 0) return BadRequest("No file uploaded"); using (var stream = file.OpenReadStream()) { await _blobStorageService.UploadBlobAsync("cv-contianer", file.FileName, stream); } return Ok("Blob uploaded successfully"); } [HttpGet("files")] public IActionResult GetFiles() { var containerClient = _blobServiceClient.GetBlobContainerClient("cv-contianer"); var blobItems = containerClient.GetBlobs(); var fileList = blobItems.Select(blobItem => blobItem.Name).ToList(); return Ok(fileList); } [HttpGet("files/{fileName}")] public async Task<IActionResult> DownloadFile(string fileName) { var containerClient = _blobServiceClient.GetBlobContainerClient("cv-contianer"); var blobClient = containerClient.GetBlobClient(fileName); var downloadResponse = await blobClient.DownloadAsync(); var stream = downloadResponse.Value.Content; return File(stream, downloadResponse.Value.ContentType, fileName); } } }
Step 7: Run the code by pressing F5 and see below is the result of file upload API.
Thanks for reading. If you like this type of content visit itsusamaarhad.com and follow on LinkedIn musama202