Site icon Tutexchange

How to integrate .NET Aspire with Azure Blob Storage

Advertisements

In this article, we are going to learn how to integrate Azure Blob Storage with .NET Aspire. As you know, .NET Aspire is used to build cloud-native applications.

What is Azure Blob Storage?

Azure Blob Storage is a cloud-based object storage service provided by Microsoft Azure for storing large amounts of unstructured data, such as text, images, videos, and backups. It is designed to be scalable, secure, and highly available for a wide range of use cases, including data archiving, content delivery, and big data analytics.

In this article, we cover:

Create a .NET Aspire Starter App

After selecting the project, click the “Next” button to proceed.

A new dialogue will appear, prompting you to configure your new project. Within this dialogue, you will be asked to provide a Solution Name and specify the location where the project should be saved.

After entering details, click the “Next” button to proceed.

A new dialogue will appear, prompting you to configure additional information related to the project, such as the framework, the .NET Aspire version, and the option to create a test project. For this demonstration, I will select .NET Aspire 9.0.

Click on the Create button to create a project.

Solution Explorer

We have created a solution, so let’s begin by adding Aspire.Hosting.Azure.Storage to the project. In this demo, we are going to configure the Aspire.Hosting.Azure.Storage.

Adding Aspire.Hosting.Azure.Storage to App Host Project

In the App Host Project, we are going to install the package Aspire.Hosting.Azure.Storage.

View after Adding Aspire.Hosting.Azure.Storage NuGet packages to the project.

After installation, we need to add resources to the Program.cs class of the AppHost project.

But we are going to use Azure blob storage for access, if we need access to Azure Blob storage, right?

Configuring Azure Blob Storage Account

In this part, we are going to learn how to create an Azure storage account and create a Container for storing blobs in it.

Steps to Create a Storage Account

  1. Navigate to Storage Accounts
    • Search for “Storage accounts” in the search bar and select it.
    • Click “Create”.
  2. Enter Basic Details
    • Subscription: Select your Azure subscription.
    • Resource Group: Choose an existing resource group or create a new one.
    • Storage Account Name: Enter a unique name (must be globally unique and lowercase).
    • Region: Select the desired region.
    • Performance: Choose Standard (for general storage) or Premium (for high-performance needs).
    • Redundancy: Select the replication type:
      • LRS (Locally Redundant Storage)
      • GRS (Geo-Redundant Storage)
      • RA-GRS (Read-Access Geo-Redundant Storage)
      • ZRS (Zone-Redundant Storage)
  3. Click “Review + Create” and then “Create”.

Steps to Configure Blob Storage

  1. After deployment, go to the Storage Account.
  2. In the left menu, select “Containers”.
  3. Click “+ Container”, enter a Container Name, and set the Public Access Level:
    • Private (default, most secure)
    • Blob (publicly readable blobs)
    • Container (publicly readable blobs and container metadata)
  4. Click “Create”.

Steps to Get Access Keys & Connection String

  1. In the Storage Account, go to “Access keys” (left menu).
  2. Copy the Connection String or Access Keys for authentication in your application.

Adding Connection String in appsettings.json

As we copy the connection string from Azure portal and add it to AspireBlob.AppHost appsettings.json

Adding changes in the Program.cs

In this part, we are going to use the AddConnectionString extension method and pass the Name of the parameter resource. The value of the connection string is read from the “ConnectionStrings:{resourcename}” ConnectionStrings(“blobs”) configuration section.

using Microsoft.Extensions.Configuration;
using static System.Reflection.Metadata.BlobBuilder;
var builder = DistributedApplication.CreateBuilder(args);
var blobs = builder.AddConnectionString("blobs");
var apiService = builder.AddProject<Projects.AspireBlob_ApiService>("apiservice")
    .WithReference(blobs);
builder.AddProject<Projects.AspireBlob_Web>("webfrontend")
    .WithExternalHttpEndpoints()
    .WithReference(apiService)
    .WaitFor(apiService);
builder.Build().Run();

Client Project (AspireBlob.ApiService)

In this AspireBlob.ApiService project, we are going to add 3 NuGet Packages.

Installing Aspire.Azure.Storage.Blobs NuGet Package

Installing Swashbuckle.AspNetCore.SwaggerGen NuGet Package

Installing Swashbuckle.AspNetCore.SwaggerUI NuGet Package

Adding BlobStorageService Class

We are going to add a class BlobStorageService.cs in the AspireBlob.ApiService in this class, we are going to inject BlobServiceClient. Using BlobServiceClient will upload a blob, delete a blob and download a blob.

Below is the source code of BlobStorageService

using Azure.Storage.Blobs;

namespace AspireBlob.ApiService
{
    public class BlobStorageService
    {
        private readonly BlobServiceClient _blobServiceClient;

        public BlobStorageService(BlobServiceClient blobServiceClient)
        {
            _blobServiceClient = blobServiceClient;
        }

        public async Task UploadBlobAsync(string containerName, string blobName, Stream content)
        {
            var containerClient = _blobServiceClient.GetBlobContainerClient(containerName);
            await containerClient.CreateIfNotExistsAsync();

            var blobClient = containerClient.GetBlobClient(blobName);
            await blobClient.UploadAsync(content, true);
        }

        public async Task<Stream> DownloadBlobAsync(string containerName, string blobName)
        {
            var containerClient = _blobServiceClient.GetBlobContainerClient(containerName);
            var blobClient = containerClient.GetBlobClient(blobName);

            var response = await blobClient.DownloadAsync();
            return response.Value.Content;
        }

        public async Task DeleteBlobAsync(string containerName, string blobName)
        {
            var containerClient = _blobServiceClient.GetBlobContainerClient(containerName);
            var blobClient = containerClient.GetBlobClient(blobName);

            await blobClient.DeleteIfExistsAsync();
        }
    }
}

Now we have added BlobStorageService class, but we need to register it in Program.cs class to inject.

builder.Services.AddScoped<BlobStorageService>();

Registering the BlobStorageService class Program.cs class

using AspireBlob.ApiService;
using Microsoft.Extensions.Azure;

var builder = WebApplication.CreateBuilder(args);

// Add service defaults & Aspire client integrations.
builder.AddServiceDefaults();

builder.AddAzureBlobClient("blobs");
// Add services to the container.
builder.Services.AddProblemDetails();

// Add API Documentation
builder.Services.AddSwaggerGen();

// Add controllers services
builder.Services.AddControllers();

builder.Services.AddScoped<BlobStorageService>();

// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();

var app = builder.Build();

// Configure the HTTP request pipeline.
app.UseExceptionHandler();

if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
}

// MapControllers is used to map the controllers to the application.
app.MapControllers();

// Register the Swagger generator and the Swagger UI middlewares
app.UseSwagger();

// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwaggerUI();

app.MapDefaultEndpoints();

app.Run();

After adding the BlobStorageService class, next we are going to add the API Controller BlobsController.

We are going to add BlobsController, in which we are going to add 3 methods.

In this, we are going to add the BlobStorageService class. Using this class, we are going to perform an activity on Azure blob storage.

BlobsController Source code

using Azure.Storage.Blobs;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace AspireBlob.ApiService
{
    [Route("api/[controller]")]
    [ApiController]
    public class BlobsController : ControllerBase
    {
        private readonly BlobStorageService _blobStorageService;

        public BlobsController(BlobStorageService blobStorageService)
        {
            _blobStorageService = blobStorageService;
        }

        [HttpPost("upload")]
        public async Task<IActionResult> Upload(IFormFile file)
        {
            using var stream = file.OpenReadStream();
            await _blobStorageService.UploadBlobAsync("mydatastore", file.FileName, stream);
            return Ok();
        }

        [HttpGet("download")]
        public async Task<IActionResult> Download(string blobName)
        {
            var stream = await _blobStorageService.DownloadBlobAsync("mydatastore", blobName);
            return File(stream, "application/octet-stream", blobName);
        }

        [HttpDelete("delete")]
        public async Task<IActionResult> Delete(string blobName)
        {
            await _blobStorageService.DeleteBlobAsync("mydatastore", blobName);
            return Ok();
        }
    }
}

After completing the integration with the API Service, we can now run the application for the first time.

This is the Dashboard for the Aspire project where you will see all applications which are running.

Call API Service for Uploading blob

As we have configured swagger in the Api service, we can see the generated document from UI calling the API service localhost URL and then appending it with the swagger keyword will land you to the swagger page.

The URL to access is your localhost application. With an appending swagger keyword at the end. https://localhost:7590/swagger/index.html

Uploading Document

Debugging View of Upload blob

Uploaded Image to Azure blob Storage

Download Image

Debug View of Download Image from Azure blob Storage

Delete Image

Debug View of Delete Image from Azure blob Storage

View After Deleting from Blob Storage

Conclusion

I hope you have liked the article. In this article, you have learned how to create an Aspire project and configure the Azure Blob Storage for uploading, downloading and deleting blobs from it.

Referenced From: Microsoft Learn – ASP.NET Core Inspire Series

GitHub Link :- https://github.com/saineshwar/Aspire_Blob

Exit mobile version