DEV Community

Joma
Joma

Posted on

Azure Blob Storage in .NET Core Web API v8

Azure Blob Storage allows us to store images as URIs on Azure and in our database as varchar/strings instead of keeping them as a Blob type.

For images

Prerequisites:

  • Installed NuGet package: Azure.Storage.Blobs

First of all, we need to register a SCOPED service in our Program.cs file:

builder.Services.AddScoped(x =>
{
    var configuration = x.GetRequiredService<IConfiguration>();
    var connectionString = configuration["AzureBlobStorage:ConnectionString"];
    if (string.IsNullOrEmpty(connectionString))
        throw new InvalidOperationException("Azure Blob Storage connection string not found.");
    return new BlobServiceClient(connectionString);
});



builder.Services.AddScoped<BlobService>();
Enter fullscreen mode Exit fullscreen mode

Then we can continue creating our service:

public class BlobService
{
    private readonly BlobContainerClient _containerClient;

    public BlobService(IConfiguration config)
    {

        var connectionString = config["ConnectionStrings:AzureBlobStorage"];
        var containerName = config["AzureBlobStorage:ContainerName"];

        if (string.IsNullOrEmpty(connectionString))
            throw new Exception("Azure Blob Storage connection string not found!");

        _containerClient = new BlobContainerClient(connectionString, containerName);

    }

    //uploading an image
    public async Task<string> UploadAsync(IFormFile file)
    {
        var blobClient = _containerClient.GetBlobClient(file.FileName);
        await blobClient.UploadAsync(file.OpenReadStream(), true);

        return blobClient.Uri.ToString();
    }


    //delete the image
    public async Task DeleteAsync(string blobUrl)
    {
        var blobName = Path.GetFileName(blobUrl);
        var blobClient = _containerClient.GetBlobClient(blobName);
        await blobClient.DeleteIfExistsAsync();
    }

}
Enter fullscreen mode Exit fullscreen mode

NOTE: connectionString and containerName are stored in appsettings.json but it would be better if they were stored as ENV values in our project.

  • BlobServiceClient: This class allows us to manipulate Azure Storage resources and blob containers
  • BlobContainerClient: This class allows us to manipulate Azure Storage containers and their blobs.
  • BlobClient: This class allows us to manipulate Azure Storage blobs. It's very crucial for us

Key steps:

  1. Creating and registering a BlobServiceClient
  2. Creating a BlobContainerClient with provided connectionString and containerName
  3. Initializing a BlobClient with our file and its name
  4. Uploading our file to the container or optionally our database using BlobClient
  5. Deleting our file from a container or optionally our database using BlobClient _____________________________________________________________

Consuming our BlobService in an API controller

Uploading an image:

var imageUrl = await _blobService.UploadAsync(novosti.FormFile);
novosti.NovostiSlikaUrl= imageUrl;
Enter fullscreen mode Exit fullscreen mode

novosti.FormFile is my object which has unmapped property FormFile which I use to handle Blob types and NovostiSlikaUrl is an object property mapped with my database's field to store these images as URI after uploading them to my Azure container.

Deleting an image:

 if (!string.IsNullOrEmpty(novostiobavijesti.BunjoNovostiSlikaUrl))
 {
     await _blobService.DeleteAsync(novostiobavijesti.BunjoNovostiSlikaUrl);
 }
Enter fullscreen mode Exit fullscreen mode

Image is deleted from a container and from my database, too.

Top comments (0)