Azure Blob Storage

Last Updated: 2018-11-20

The Azure Blob Storage handles uploaded media by storing the uploaded files in an Azure Storage Service. If you're hosting your web application in Azure this has several benefits.

  • Dedicated storage is much cheaper than App Service storage.
  • Traffic from dedicated storage is much cheaper the App Service bandwidth.
  • Media files are distributed and is not stored together with the web application.
  • It's very easy to connect Azure CDN to Blob Storage.

As the media files are stored in a central location this works well when the different components of the application (such as client and manager) are deployed to different locations.

Installation

The Azure Blob Storage can be installed by adding the NuGet package:

Piranha.Azure.BlobStorage

Registering The Service

You register Local File Storage with the default configuration in ConfigureServices() with the following code:

services.AddPiranhaBlobStorage(credentials);

Manual configuration

The storage credentials can be created manually by providing the storage service name and key.

var credentials = new StorageCredentials(storageName, storageKey);

Using appsettings.json

You can easily configure your credentials from your appsettings.json by adding a section like this:

{
"Storage": {
"Name": "MyStorageName",
"Key": "MyStorageKey"
}
}

Given that you've setup your app configuration you can then access it like this from your ConfigureServices.

public class Startup
{
public IConfiguration Configuration { get; private set; }

public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
Configuration = builder.Build();
}

public void ConfigureServices(IServiceCollection services)
{
...

services.AddPiranhaBlobStorage(new StorageCredentials(
Configuration["Storage:Name"],
Configuration["Storage:Key"]
));

...
}
}

By adding AddEnvironmentVariables you can override the settings in the Azure Portal by adding the corresponding App Settings.

Additional Configuration

When registering the service you have access to some configuration options to customize the storage to your needs.

Container Name

services.AddPiranhaBlobStorage(credentials, containerName: "dev");

The container name in the Storage Service where uploaded media assets will be stored.

Scope

services.AddPiranhaBlobStorage(credentials, scope: ServiceLifetime.Scoped);

By default the service is registered as a Singleton, but in some cases you might want to handle it differently in your application.