30 April 2024

Azure Blob Storage

 Azure Blob Storage

Azure Blob Storage is a service from Microsoft Azure that allows you to store large amounts of unstructured data, such as text or binary data, which is accessible from anywhere in the world via HTTP or HTTPS. Integrating Azure Blob Storage with a Web API in C# involves several steps. Here, I’ll guide you through creating a simple Web API that can upload files to Azure Blob Storage, list blobs in a container, and download blobs.


### Step 1: Create an Azure Blob Storage Account
First, you need to create an Azure Storage account through the Azure portal. Once created, obtain the access keys and connection string from the portal, as these will be needed to access your Blob Storage from the API.

### Step 2: Set Up Your Web API Project
1. **Create a new ASP.NET Core Web API project** in Visual Studio.
2. **Install the Azure Storage SDK** by running the following NuGet command:

   ```bash
   Install-Package Azure.Storage.Blobs
   ```

### Step 3: Configure the Storage Connection
Add your storage connection string to the `appsettings.json` file:

```json
{
  "AzureStorageConfig": {
    "ConnectionString": "DefaultEndpointsProtocol=https;AccountName=youraccountname;AccountKey=youraccountkey;EndpointSuffix=core.windows.net"
  }
}
```

### Step 4: Create the Blob Service Client
Create a service class that will handle operations related to Blob storage:

```csharp
using Azure.Storage.Blobs;
using Microsoft.Extensions.Configuration;

public class BlobService
{
    private readonly BlobServiceClient _blobServiceClient;

    public BlobService(IConfiguration configuration)
    {
        var connectionString = configuration.GetConnectionString("AzureStorageConfig");
        _blobServiceClient = new BlobServiceClient(connectionString);
    }

    public async Task UploadFileBlobAsync(string blobContainerName, Stream content, string contentType, string fileName)
    {
        var containerClient = _blobServiceClient.GetBlobContainerClient(blobContainerName);
        await containerClient.CreateIfNotExistsAsync();
        var blobClient = containerClient.GetBlobClient(fileName);
        await blobClient.UploadAsync(content, new Azure.Storage.Blobs.Models.BlobHttpHeaders { ContentType = contentType });
    }

    public async Task<IEnumerable<string>> ListBlobsAsync(string blobContainerName)
    {
        var containerClient = _blobServiceClient.GetBlobContainerClient(blobContainerName);
        var blobs = new List<string>();

        await foreach (var blobItem in containerClient.GetBlobsAsync())
        {
            blobs.Add(blobItem.Name);
        }

        return blobs;
    }

    public async Task<Stream> GetBlobAsync(string blobContainerName, string blobName)
    {
        var containerClient = _blobServiceClient.GetBlobContainerClient(blobContainerName);
        var blobClient = containerClient.GetBlobClient(blobName);
        var downloadInfo = await blobClient.DownloadAsync();

        return downloadInfo.Value.Content;
    }
}
```

### Step 5: Expose API Endpoints
Modify the `Controllers` to use `BlobService`:

```csharp
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("[controller]")]
public class BlobController : ControllerBase
{
    private readonly BlobService _blobService;

    public BlobController(BlobService blobService)
    {
        _blobService = blobService;
    }

    [HttpPost("upload")]
    public async Task<IActionResult> UploadFile([FromForm]IFormFile file)
    {
        using (var stream = file.OpenReadStream())
        {
            await _blobService.UploadFileBlobAsync("your-container-name", stream, file.ContentType, file.FileName);
        }
        return Ok();
    }

    [HttpGet("list")]
    public async Task<IActionResult> ListBlobs()
    {
        var blobs = await _blobService.ListBlobsAsync("your-container-name");
        return Ok(blobs);
    }

    [HttpGet("download/{blobName}")]
    public async Task<IActionResult> DownloadBlob(string blobName)
    {
        var stream = await _blobService.GetBlobAsync("your-container-name", blobName);
        return File(stream, "application/octet-stream", blobName);
    }
}
```

### Step 6: Register BlobService in Startup.cs
In `Startup.cs`, add:

```csharp
services.AddSingleton<BlobService>();

No comments:

Post a Comment

Comments Welcome

Implementing OAuth validation in a Web API

 I mplementing OAuth validation in a Web API Implementing OAuth validation in a Web API using C# typically involves several key steps to sec...