azure function c# http trigger blob output

This is a combined HTTP triggered function with a output blob binding:

[FunctionName("HttpTriggeredFunction")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest httpRequest,
    [Blob("blobcontainer", Connection = "StorageConnectionString")] CloudBlobContainer outputContainer,
    ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    await outputContainer.CreateIfNotExistsAsync();

    var requestBody = await new StreamReader(httpRequest.Body).ReadToEndAsync();
    var blobName = Guid.NewGuid().ToString();

    var cloudBlockBlob = outputContainer.GetBlockBlobReference(blobName);
    await cloudBlockBlob.UploadTextAsync(requestBody);

    return new OkObjectResult(blobName);
}

It uses the CloudBlobContainer output type to get a reference to the blob container which then enables you to use methods such as .GetBlockBlobReference("blobPath") to get a reference to a blob.

Once you have a reference to a blob, you can use different methods to upload:

  • cloudBlockBlob.UploadFromByteArrayAsync()
  • cloudBlockBlob.UploadFromFileAsync()
  • cloudBlockBlob.UploadTextAsync()
  • cloudBlockBlob.UploadFromStreamAsync()

To get it running locally, you need set some things up. Notice in my example the attribute [Blob("blobcontainer", Connection = "StorageConnectionString")]

  • "blobcontainer" this can be whatever you want and will be the name of the container that will be created in your storage account by this line outputContainer.CreateIfNotExistsAsync(); (if it doesn't exist already).
  • Connection = "StorageConnectionString" this can be a setting in your local.settings.json for the connection string of your storage account. When developing locally I would recommend setting this to "UseDevelopmentStorage=true" so that you can take advantage of the storage emulator. Then when you are ready to deploy onto Azure, you would create a setting in the function app containing the real connection string.

local.settings.json

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",

    "StorageConnectionString": "UseDevelopmentStorage=true"
  }
}