Search code examples
c#azureconfiguration-filestest-data

How can I get a BLOB and add it to my configuration?


I have a web api that uses a bunch of appSettings files to load test data. I want to shift the location of that data to an Azure Blob. Based on the test infrastructure, I'd like to convert the Blob into an IConfiguration object.

To accomplish this, I wanted to use the AddJsonStream onto a ConfigurationBuilder.

I created this method to go out and grab the blob and convert it to a stream:

    public static Stream GetBlobAsStream(Uri blobURI)
    {
        var storageAccount = CloudStorageAccount.Parse(AZURE_STORAGE_CONNECTION_STRING);
        var cloudBlobClient = storageAccount.CreateCloudBlobClient();
        var cloudBlobContainer = cloudBlobClient.GetContainerReference(blobContainer);
        var cloudBlob = cloudBlobContainer.GetBlockBlobReference(blobName);
        var stream = cloudBlob.OpenRead();
        return stream;
    }

Now this method uses a bunch of hard coded constants - which I'd like to remove. How can I remove the hard coding, and find the needed azure info based on the Environment in which it's being run? Or have I programmed myself into a corner here?


Solution

  • You could try to create an instance of CloudBlockBlob using the Blob URI and Blob Client by doing something like:

    public static Stream GetBlobAsStream(Uri blobURI)
    {
        var storageAccount = CloudStorageAccount.Parse(AZURE_STORAGE_CONNECTION_STRING);
        var cloudBlobClient = storageAccount.CreateCloudBlobClient();
        var cloudBlob = new CloudBlockBlob(blobURI, cloudBlobClient);
        var stream = cloudBlob.OpenRead();
        return stream;
    }
    

    or create an instance of CloudBlockBlob using the Blob URI and Storage Credentials by doing something like:

    public static Stream GetBlobAsStream(Uri blobURI)
    {
        var storageAccount = CloudStorageAccount.Parse(AZURE_STORAGE_CONNECTION_STRING);
        var cloudBlob = new CloudBlockBlob(blobURI, storageAccount.Credentials);
        var stream = cloudBlob.OpenRead();
        return stream;
    }