Search code examples
c#azureazure-functionsprecompiled

Bind to custom input properties in C# Precompiled Azure Functions


I am attempting to use Custom Bindings and Patterns to Create an HTTP Triggered Azure Function that gets a file from Blob Storage. In my case the POST HTTP Request would know the attachment name. In this article the documents discuss the pattern using csx scripting, I am using the Precomipled C# Azure Functions in Visual Studio. I tried to translate it to the following but it throws a run-time exception:

The following 1 functions are in error: Run: Microsoft.Azure.WebJobs.Host: Error indexing method 'HttpTriggerGetAttachmentBlob.Run'. Microsoft.Azure.WebJobs.Host: No binding parameter exists for 'Attachment'.

Here is the Code:

    public class BlobInfo
    {
        public string Attachment { get; set; }
    }
    public static class HttpTriggerGetAttachmentBlob
    {
        [FunctionName("HttpTriggerGetAttachmentBlob")]
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function,
            "post")]
            HttpRequestMessage req, 
            TraceWriter log,
            [Blob("strings/{Attachment}")] string blobContents,
            BlobInfo blobInfo)
        {
            if(blobContents == null) {
                return req.CreateResponse(HttpStatusCode.NotFound);
            }

            return req.CreateResponse(HttpStatusCode.OK, new
            {
                data = $"{blobContents}"
            });
        }
    }

How does one retrieve a Blob Storage file knowing the filename coming in from a Triggered event?


Solution

  • The trick is actually to put HttpTrigger attribute on blobInfo parameter, not req:

    public static async Task<HttpResponseMessage> Run(HttpRequestMessage req,
      TraceWriter log,
      [Blob("strings/{Attachment}")] string blobContents,
      [HttpTrigger(AuthorizationLevel.Function, "post")] BlobInfo blobInfo)
    

    That will tell runtime that you are binding to BlobInfo class, and it will be able to derive {Attachment} template binding.

    Note: be sure to delete bin folder before you recompile, the tooling doesn't always update the existing function.json file properly.