8

Can someone describe me how I can configure a C# azure function which uses an HTTP input trigger and a blob storage output trigger?

Maybe also with an example code snippet and an example function.json. I don't get it to work locally with the azure functions core tools.

2
  • you are looking for function 2.x sample? Commented Jun 25, 2019 at 2:19
  • yes preferable. but if easier with 1x also possible Commented Jun 25, 2019 at 2:32

4 Answers 4

22

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"
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hey, do you know by any chance to use CloudBlobContainer outputContainer in isolated model?
4

to make an http function that saves to Blob Storage use this code:

 #r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log,TextWriter outputBlob)
{
   
    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    outputBlob.WriteLine(requestBody);
 
    string result =  "{ 'result':  'ok' }";
    dynamic data = JsonConvert.DeserializeObject(result);
      
    return new OkObjectResult(data);
}
 

You need to set the output binding:

enter image description here

You can then run a test posting content on the test window

enter image description here

Comments

0

This is the simplest code to accomplish this task.

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;

public static IActionResult Run(HttpRequest req, out string outputBlob)
{
    outputBlob = "This is a Blob content";
    return new OkResult();
}

The input and output parameters are specified in the function.json file and are additionally presented graphically in the Integration tab.

function.json file content:

{"bindings":[{"authLevel": "ANONYMOUS",
    "name": "req",
    "type": "httpTrigger",
    "direction": "in",
    "methods": ["get","post"]
},{
    "name": "$return",
    "type": "http",
    "direction": "out"
},{
    "name": "outputBlob",
    "direction": "out",
    "type": "blob",
    "path": "outcontainer/{rand-guid}",
    "connection": "AzureWebJobsStorage"
}]}

Integration tab content: enter image description here

local.settings.json file content

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

The function can be extended by adding logging and reading data from the request.

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using System;

public static IActionResult Run(HttpRequest req, out string outputBlob, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");
    outputBlob = $"This Blob was created by HttpTrigger1 because at {DateTime.Now} request was sent to: {req.Host}";
    return new OkResult();
}

Comments

-1

Everything you need is there in the Official docs page,

(i) Http and WebHooks

(ii)Output binding blob storage

Http Trigger Sample code

[FunctionName("HttpTriggerCSharp")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] 
    HttpRequest req, ILogger log)

Blob Storage Output binding

[FunctionName("ResizeImage")]
public static void Run(
    [BlobTrigger("sample-images/{name}")] Stream image,
    [Blob("sample-images-sm/{name}", FileAccess.Write)] Stream imageSmall,
    [Blob("sample-images-md/{name}", FileAccess.Write)] Stream imageMedium)

1 Comment

thanks for the answer. What I need is this combined. the problem is that I can not add to a variable like "out string myOutputBlob" to the run function containing and HttpTrigger.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.