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.
- using System;
- using System.IO;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Azure.WebJobs;
- using Microsoft.Azure.WebJobs.Extensions.Http;
- using Microsoft.AspNetCore.Http;
- using Microsoft.Extensions.Logging;
- using Newtonsoft.Json;
- using Microsoft.Azure.Storage;
- using Microsoft.Azure.Storage.Blob;
- using Microsoft.Extensions.Configuration;
-
- namespace AzFunctions
- {
- public static class UploadBlobHttpTriggerFunc
- {
- [FunctionName("UploadBlobHttpTriggerFunc")]
- public static async Task<IActionResult> Run(
- [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
- ILogger log, ExecutionContext context)
- {
- log.LogInformation($"C# Http trigger function executed at: {DateTime.Now}");
- CreateContainerIfNotExists(log, context);
-
- CloudStorageAccount storageAccount = GetCloudStorageAccount(context);
- CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
- CloudBlobContainer container = blobClient.GetContainerReference("dummy-messages");
-
- for (int i = 1 ; i <= 5; i++)
- {
- string randomStr = Guid.NewGuid().ToString();
- CloudBlockBlob blob = container.GetBlockBlobReference(randomStr);
-
- var serializeJesonObject = JsonConvert.SerializeObject(new { ID = randomStr, Content = $"<html><body><h2> This is a Sample email content {i}! </h2></body></html>" });
- blob.Properties.ContentType = "application/json";
-
- using (var ms = new MemoryStream())
- {
- LoadStreamWithJson(ms, serializeJesonObject);
- await blob.UploadFromStreamAsync(ms);
- }
- log.LogInformation($"Bolb {randomStr} is uploaded to container {container.Name}");
- await blob.SetPropertiesAsync();
- }
-
- return new OkObjectResult("UploadBlobHttpTrigger function executed successfully!!");
- }
-
- private static void CreateContainerIfNotExists(ILogger logger, ExecutionContext executionContext)
- {
- CloudStorageAccount storageAccount = GetCloudStorageAccount(executionContext);
- CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
- string[] containers = new string[] { "dummy-messages" };
- foreach (var item in containers)
- {
- CloudBlobContainer blobContainer = blobClient.GetContainerReference(item);
- blobContainer.CreateIfNotExistsAsync();
- }
- }
-
- private static CloudStorageAccount GetCloudStorageAccount(ExecutionContext executionContext)
- {
- var config = new ConfigurationBuilder()
- .SetBasePath(executionContext.FunctionAppDirectory)
- .AddJsonFile("local.settings.json", true, true)
- .AddEnvironmentVariables().Build();
- CloudStorageAccount storageAccount = CloudStorageAccount.Parse(config["CloudStorageAccount"]);
- return storageAccount;
- }
- private static void LoadStreamWithJson(Stream ms, object obj)
- {
- StreamWriter writer = new StreamWriter(ms);
- writer.Write(obj);
- writer.Flush();
- ms.Position = 0;
- }
- }
- }
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
- "Values": {
- "AzureWebJobsStorage": "UseDevelopmentStorage=true",
- "FUNCTIONS_WORKER_RUNTIME": "dotnet",
- "CloudStorageAccount": "DefaultEndpointsProtocol=https;AccountName=;AccountKey=;EndpointSuffix=core.windows.net",
- }
Let’s build and run the function and test in local. You will see the below window open.
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.
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.
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.
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.
Give Name to function app, select resource group and azure storage => Click on Create.
Now select Azure Function app => Click on Finish.
Now Click on Configure => Select Storage account and click on Next => Click Finish
Finally, we are ready to publish. Click on Publish. Once it’s done, check on Azure portal.
On Azure portal, you will see the newly created Azure function.
Let’s modify the configuration to add additional settings as “CloudStorageAccount” and copy connection string value from storage account and click on save.
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.
Once it's successful, let's cross verify the uploaded content on container into storage account.
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!