Adventures with Azure Storage: Read/Write Files to Blob Storage from a .NET Core Web API

azure storage

I wanted to share some code I wrote recently for uploading a file to a .NET Core Web API and writing it to Blob Storage, as well as, downloading the file from the .NET Core Web API.

As a bonus, we will use SAS tokens to read and write to Blob Storage.

Let’s get started.

Create an Azure Storage account or use an existing one.

Open Visual Studio or VS Code and Create a new .NET Core Web API project.

Add a folder called Helpers.

Add two files, one called AzureStorageBlobOptions.cs and another called AzureStorageBlobOptionsTokenGenerator.cs.

Configuration will be provided by AzureStorageBlobOptions and the SAS Token will be generated by AzureStorageBlobOptionsTokenGenerator.

In the appsettings.Development.json, Add a section called AzureStorageBlobOptions and Add configuration keys and Update the key values based on your Azure Storage account and Blob container.

In the Startup.cs file add dependency injection support for the AzureStorageBlobOptions and AzureStorageBlobOptionsTokenGenerator classes.

In the Controllers folder, Add a controller called FilesController.

Update the FilesController constructor to accept two parameters, one for AzureStorageBlobOptions and AzureStorageBlobOptionsTokenGenerator.

Add a PostAsync method to support file upload, you will also want to add a Consumes attribute to handle the file upload.

Add a GetAsync method to support file download.

Run the Web API.

Open Postman, and Create a new POST request.

Enter the API URL, in my case it was https://localhost:44327/api/files.

Set Body to form-data.

Add a key called file, make sure to change the type to File, defaults to Text.

Add the file to upload and Send the request.

If the call is successful, you should receive an OK response with the new name of the file uploaded.

Now to download the file.

Create a new GET request in Postman.

Enter the API URL, in my case it was https://localhost:44327/api/files/RETURN_FILE_NAME, and Send the request.

If the call is successful, you should see the image displayed in Postman.

Thanks for reading! And please feel free to share any feedback, it is much appreciated!


Discover more from Matt Ruma

Subscribe to get the latest posts sent to your email.

3 Replies to “Adventures with Azure Storage: Read/Write Files to Blob Storage from a .NET Core Web API”

  1. Hello Sir,
    Thanks for the article.
    But then i tried this code, IOptions in AzureStorageBlobOptions is throwing an error.
    “Using the generic type IOptions requires 1 type arguments.

    Any help is greatly appreciated.

Leave a Reply

Your email address will not be published. Required fields are marked *