How to use Azure Blob Storage in your .NET Core Application

Intro

Azure Blob Storage account is a cloud-based storage service that provides secure, cost-effective, and highly scalable storage for unstructured data. It is a great way to store large amounts of data securely and reliably. With an Azure Blob Storage account, you can store files, images, videos, audio files, and other types of documents with ease. It also allows you to easily share your data with other users and applications. Whether you need to store large amounts of data or just a few files, Azure Blob Storage account is the perfect solution for your needs.


Before going further, if you don't have a Azure Blob Storage prepared, create and manage one on Azure Portal - visit this topic for more information.



Integrate Azure Blob Storage NuGet packages in your application

Firstly, in order to upload and download files in and from the Storage Account - the core packages needs to be integrated into your project as specified.


Install Azure Storage Blobs NuGet Package



Blob Storage client - Interface

A Blob Storage client interface is being created in order to use it through the entire project using the dependency injection design pattern.


public interface IBlobStorageClient
{
    Task<byte[]> DownloadFileAsync(string fileName);
    Task UploadFileAsync(string fileName, byte[] content);
    Task DeleteFileAsync(string fileName);
}



Blob Storage client - Implementation

The actual implementation of the previously created interface where all the logic for Azure Blob Storage usage is placed and ready to go.

Sensitive data like connection strings are coming through a dynamic configuration provider, which can be either the local application settings file or a 3rd party secure secret storage. For security purposes, we advice everyone to store sensitive data in places with enhanced involvement in security like Azure Key Vault.


public class BlobStorageClient : IBlobStorageClient
{
    private readonly BlobServiceClient _client;
    private readonly string _containerName;

    public BlobStorageClient(IConfiguration configuration)
    {
        _client = new BlobServiceClient(configuration["AzureStorageConnectionString"]);
        _containerName = configuration["AzureStorageContainer"];
    }

    public async Task<byte[]> DownloadFileAsync(string fileName)
    {
        var containerClient = _client.GetBlobContainerClient(_containerName);
        var blobClient = containerClient.GetBlobClient(fileName);

        using (var stream = new MemoryStream())
        {
            await blobClient.DownloadToAsync(stream);
            return stream.ToArray();
        }
    }

    public async Task UploadFileAsync(string fileName, byte[] content)
    {
        var containerClient = _client.GetBlobContainerClient(_containerName);
        var blobClient = containerClient.GetBlobClient(fileName);

        using (var stream = new MemoryStream(content))
        {
            await blobClient.UploadAsync(stream);
        }
    }

	public async Task DeleteFileAsync(string fileName)
	{
		var containerClient = _client.GetBlobContainerClient(_containerName);
		var blobClient = containerClient.GetBlobClient(fileName);

        await blobClient.DeleteIfExistsAsync();
	}
}


The first implemented method called DownloadFileAsync downloads a file from an Azure Blob Storage container and returns its contents as a byte array. Here's how the code works:

    1. The method takes a file name as a parameter and declares a local variable named containerClient that represents the Blob Storage container client. The _client variable is assumed to be an instance of BlobServiceClient, which is provided by the Azure.Storage.Blobs NuGet package.
    2. The method then declares a local variable named blobClient that represents the blob client for the specified file. The GetBlobClient method is used to create this client by passing in the file name.
    3. The using statement creates a MemoryStream instance that will be used to store the contents of the downloaded file.
    4. The DownloadToAsync method is called on the blobClient instance to download the file contents and write them to the MemoryStream. This method is an asynchronous operation that reads the contents of the blob and writes them to the provided stream.
    5. The method returns the contents of the MemoryStream as a byte array by calling the ToArray method on the stream.


The second implemented method called UploadFileAsync uploads a file to an Azure Blob Storage container. Here's how the code works:

    1. The method takes two parameters: a file name and a byte array representing the file content.
    2. The method declares a local variable named containerClient that represents the Blob Storage container client. The _client variable is assumed to be an instance of BlobServiceClient, which is provided by the Azure.Storage.Blobs NuGet package.
    3. The method then declares a local variable named blobClient that represents the blob client for the specified file. The GetBlobClient method is used to create this client by passing in the file name.
    4. The using statement creates a MemoryStream instance that will be used to upload the file contents.
    5. The MemoryStream is initialized with the content byte array provided as a parameter.
    6. The UploadAsync method is called on the blobClient instance to upload the contents of the MemoryStream to the blob. This method is an asynchronous operation that reads the contents of the stream and writes them to the blob.


The third and the last implemented method called DeleteFileAsync deletes a file from an Azure Blob Storage container. Here's how the code works:

    1. The method takes a file name as a parameter.
    2. The method declares a local variable named containerClient that represents the Blob Storage container client. The _client variable is assumed to be an instance of BlobServiceClient, which is provided by the Azure.Storage.Blobs NuGet package.
    3. The method then declares a local variable named blobClient that represents the blob client for the specified file. The GetBlobClient method is used to create this client by passing in the file name.
    4. The DeleteIfExistsAsync method is called on the blobClient instance to delete the file. This method is an asynchronous operation that deletes the blob from the container if it exists.



Shared Access Signatures (SAS)

Azure Shared Access Signature (SAS) is a secure way to grant access to data stored in Azure Storage without sharing the storage account key. With SAS, you can grant limited access to data in your storage accounts for a specified period of time. It is an ideal solution for granting access to large amounts of data stored in the cloud without having to share the account keys with third parties.

Example of how to implement a SAS Uri generation based on an existing blob in Azure Storage which is read-only and will expire after 10 minutes from generation.


private string GenerateSharedAccessSignatureUri(BlobClient blobClient)
{
    if (blobClient.CanGenerateSasUri)
    {
        var sasBuilder = new BlobSasBuilder()
        {
            BlobContainerName = blobClient.GetParentBlobContainerClient().Name,
            BlobName = blobClient.Name,
            Resource = "b",
            ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(10),
        };

        sasBuilder.SetPermissions(BlobAccountSasPermissions.Read);

        var uri = blobClient.GenerateSasUri(sasBuilder);

        return uri.ToString();
    }

    return string.Empty;
}



Conclusions

Azure Blob Storage provides an ideal solution for businesses looking for a secure and reliable way to store large amounts of unstructured data in the cloud. It is highly scalable and cost-effective, making it an attractive option for businesses of all sizes. Additionally, its robust security features make it an ideal choice for storing sensitive information in the cloud.