Create Container And Upload Blob Using Azure Function In .NET Core

Introduction

 
This article demonstrates how to create a container and upload blob content into the container using Azure Function. Azure function is nothing but a static class with Run method where all logic executed sequentially. We will build an Http Trigger Azure function using ASP.NET Core.
 
Prerequisites
  • Basic Knowledge on Azure Function
  • Azure storage account already created
  • .NET Core SDK 3.1 installed in your PC.
  • Azure storage emulator installed. This is available as part of the Microsoft Azure SDK. Check here for more details.

Create Http trigger function using Visual Studio

 
First, we will create Azure Function app empty project from Visual Studio. Give the solution a name and project name as per your wish. Here, I have given project name as "AzFunctions".
 
Create Container and Upload Blob using Azure Function in .NET Core
 
 Create Container and Upload Blob using Azure Function in .NET Core
 
Select Empty template here.
 
Create Container and Upload Blob using Azure Function in .NET Core
 
Once newly created solution is loaded, right click on function project => Click on Add => Click on New Azure Function… => Give function name as “UploadBlobHttpTriggerFunc.cs” => Click on Add => Select “Http Trigger” => Click on Create.
 
Create Container and Upload Blob using Azure Function in .NET Core
 
Now we need to install the required NuGet packages into the function app project. For that, right click on the project => Click on Manage NuGet Packages… => Browse and install one by one. Below screenshot for reference.
  • Microsoft.Azure.WebJobs
  • Microsoft.Azure.WebJobs.Extensions.Storage
Create Container and Upload Blob using Azure Function in .NET Core
 
So far we have created a function app project with Http trigger function with default template and installed the required NuGet packages.
 
Now we are going to write the actual operation performed by the function. As I already mentioned, the purpose of this function is to create container and upload some JSON blob content into the container.
 
Add additional parameter into function Run method as ExecutionContext which will give the possibility to use of ConfigurationBuilder so that Azure function can read storage connection string from Json file or from function configuration settings on Azure.
 
The below sequential actions will be performed by this function,
  1. Create container called “dummy-messages” if not exists into storage account
  2. Create an object with unique Id and upload that as JSON object into container. This is just a demo content uploaded though loop. Based on your need, you can create your own JSON object.
UploadBlobHttpTriggerFunc.cs
  1. using System;  
  2. using System.IO;  
  3. using System.Threading.Tasks;  
  4. using Microsoft.AspNetCore.Mvc;  
  5. using Microsoft.Azure.WebJobs;  
  6. using Microsoft.Azure.WebJobs.Extensions.Http;  
  7. using Microsoft.AspNetCore.Http;  
  8. using Microsoft.Extensions.Logging;  
  9. using Newtonsoft.Json;  
  10. using Microsoft.Azure.Storage;  
  11. using Microsoft.Azure.Storage.Blob;  
  12. using Microsoft.Extensions.Configuration;  
  13.   
  14. namespace AzFunctions  
  15. {  
  16.     public static class UploadBlobHttpTriggerFunc  
  17.     {  
  18.         [FunctionName("UploadBlobHttpTriggerFunc")]  
  19.         public static async Task<IActionResult> Run(  
  20.             [HttpTrigger(AuthorizationLevel.Function, "get""post", Route = null)] HttpRequest req,  
  21.             ILogger log, ExecutionContext context)  
  22.         {  
  23.             log.LogInformation($"C# Http trigger function executed at: {DateTime.Now}");  
  24.             CreateContainerIfNotExists(log, context);  
  25.   
  26.             CloudStorageAccount storageAccount = GetCloudStorageAccount(context);  
  27.             CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();  
  28.             CloudBlobContainer container = blobClient.GetContainerReference("dummy-messages");  
  29.   
  30.             for (int i = 1 ; i <= 5; i++)  
  31.             {  
  32.                 string randomStr = Guid.NewGuid().ToString();  
  33.                 CloudBlockBlob blob = container.GetBlockBlobReference(randomStr);  
  34.   
  35.                 var serializeJesonObject = JsonConvert.SerializeObject(new { ID = randomStr, Content = $"<html><body><h2> This is a Sample email content {i}! </h2></body></html>" });  
  36.                 blob.Properties.ContentType = "application/json";  
  37.   
  38.                 using (var ms = new MemoryStream())  
  39.                 {  
  40.                     LoadStreamWithJson(ms, serializeJesonObject);  
  41.                     await blob.UploadFromStreamAsync(ms);  
  42.                 }  
  43.                 log.LogInformation($"Bolb {randomStr} is uploaded to container {container.Name}");  
  44.                 await blob.SetPropertiesAsync();  
  45.             }  
  46.   
  47.             return new OkObjectResult("UploadBlobHttpTrigger function executed successfully!!");  
  48.         }  
  49.   
  50.         private static void CreateContainerIfNotExists(ILogger logger, ExecutionContext executionContext)  
  51.         {  
  52.             CloudStorageAccount storageAccount = GetCloudStorageAccount(executionContext);  
  53.             CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();  
  54.             string[] containers = new string[] { "dummy-messages" };  
  55.             foreach (var item in containers)  
  56.             {  
  57.                 CloudBlobContainer blobContainer = blobClient.GetContainerReference(item);  
  58.                 blobContainer.CreateIfNotExistsAsync();  
  59.             }  
  60.         }  
  61.   
  62.         private static CloudStorageAccount GetCloudStorageAccount(ExecutionContext executionContext)  
  63.         {  
  64.             var config = new ConfigurationBuilder()  
  65.                             .SetBasePath(executionContext.FunctionAppDirectory)  
  66.                             .AddJsonFile("local.settings.json"truetrue)  
  67.                             .AddEnvironmentVariables().Build();  
  68.             CloudStorageAccount storageAccount = CloudStorageAccount.Parse(config["CloudStorageAccount"]);  
  69.             return storageAccount;  
  70.         }  
  71.         private static void LoadStreamWithJson(Stream ms, object obj)  
  72.         {  
  73.             StreamWriter writer = new StreamWriter(ms);  
  74.             writer.Write(obj);  
  75.             writer.Flush();  
  76.             ms.Position = 0;  
  77.         }  
  78.     }  
  79. }  
Open local.settings.json and add CloudStorageAccount connection string which is required for testing from local.
 
This value can be found from your Azure storage account. For that, login to Azure account => Go to storage account => Click on Access Keys under settings on left menu => You will see two keys there => Copy anyone of the connection sting => Paste that into local.settings.json
  1. "Values": {  
  2.     "AzureWebJobsStorage""UseDevelopmentStorage=true",  
  3.     "FUNCTIONS_WORKER_RUNTIME""dotnet",  
  4.     "CloudStorageAccount""DefaultEndpointsProtocol=https;AccountName=;AccountKey=;EndpointSuffix=core.windows.net",  
  5.   }   
Let’s build and run the function and test in local. You will see the below window open.
 
Create Container and Upload Blob using Azure Function in .NET Core
 
While running function app project in local after pressing F5, if you see below error, you may need to start Azure storage emulator from start menu of your PC.
 
Create Container and Upload Blob using Azure Function in .NET Core
 
If emulator cmd is giving error and failed to create local storage instance, you can run AzureStorageEmulator.exe start –inprocess in emulator cmd to bypass it as of now.
 
Create Container and Upload Blob using Azure Function in .NET Core
 
Now copy the http url from local function console window (in my case it is http://localhost:7071/api/UploadBlobHttpTriggerFunc) and paste it into the browser. Once it is executed, you will see message “UploadBlobHttpTrigger function executed successfully!!” which we actually returned from the function. And if you look at the storage account in Azure portal, you will see container is created and blob messages are uploaded.
 
Awesome! Let's deploy the function.
 

Deploy Azure Function from Visual Studio

 
We are now ready to publish our function app to Azure. For that, right click on project and click on Publish… => Select Target as Azure => Click on Next => Select specific target as Azure Function App (Windows) => Click on Next => Select your azure account to log in.
 
 Create Container and Upload Blob using Azure Function in .NET Core
 
Create Container and Upload Blob using Azure Function in .NET Core 
Create Container and Upload Blob using Azure Function in .NET Core
 
Once you logged in and select your Azure account from visual studio it's time to  create Azure function app. 
 
If you already created function App from Azure or if you have existing function app, then you can directly select that, otherwise you can create new Azure Function app by clicking on “Create a new Azure Function…” option.
 
Create Container and Upload Blob using Azure Function in .NET Core
 
Give Name to function app, select resource group and azure storage => Click on Create.
 
 Create Container and Upload Blob using Azure Function in .NET Core
 
Now select Azure Function app => Click on Finish.
 
Create Container and Upload Blob using Azure Function in .NET Core
 
Now Click on Configure => Select Storage account and click on Next => Click Finish
 
Create Container and Upload Blob using Azure Function in .NET Core
 
 Finally, we are ready to publish. Click on Publish. Once it’s done, check on Azure portal.
 
 Create Container and Upload Blob using Azure Function in .NET Core 
 
On Azure portal, you will see the newly created Azure function.
 
 Create Container and Upload Blob using Azure Function in .NET Core
 
Let’s modify the configuration to add additional settings as “CloudStorageAccount” and copy connection string value from storage account and click on save.
 
Create Container and Upload Blob using Azure Function in .NET Core
 

Test Azure Function

 
Now we can test the function, navigate to function and click on “Click+Test” => Click on Test/Run to run it. You can alternatively run by hitting the url. For that, you can click on "Get function url" and copy and paste url into the browser.
 
 Create Container and Upload Blob using Azure Function in .NET Core
 
Once it's successful, let's cross verify the uploaded content on container into storage account.
 
 Create Container and Upload Blob using Azure Function in .NET Core
 
Excellent! We  created and tested Http trigger function and deployed it to Azure.
 

Summary

 
In this article, we created a container and uploaded sample blob though Azure http trigger function using .NET Core. Also we have seen how to deploy an Azure Function from Visual Studio itself step by step and tested the function from Azure portal. I hope you find this article useful!