Azure Functions: binding to a property
By rickvdbosch
- 2 minutes read - 333 wordsHere’s a short post I didn’t want to hold from you. As you may already know I wrote a blogpost on Using Triggers & Bindings in Azure Functions. It handles quite a few nice possibilities of using triggers and bindings in Azure Functions (if I may say so myself… 😳). Fortunately, you learn something new every day. So I learned about Property Binding recently…
Property Binding
Like in the HttpTriggerReturnBinding
example in the functions-triggers-bindings-example GitHub repository, let’s say we have a model RequestModel
that we’re receiving through a POST on an HttpTriggered Function. Here’s the RequestModel
class:
public class RequestModel
{
public string Message { get; set; }
public string Identifier { get; set; }
}
This model is automatically deserialized from the POST body by the platform: if you bind the HttpTrigger
to a parameter of type RequestModel
, it will be available in your Function:
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] RequestModel model
Like that’s not enough magic already, let’s sprinkle that with an extra bit of …
Let’s suppose you would like your Output Binding to use the value of the Identifier
property as the name for the Blob to bind against…? No problem! You can do so like this:
[FunctionName(nameof(HttpTriggerPropertyBinding))]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] RequestModel model,
[Blob("properties/{Identifier}.txt", FileAccess.Write, Connection = "scs")] Stream stream,
ILogger log)
{
using var writer = new StreamWriter(stream);
await writer.WriteLineAsync($"Message:\t{model.Message}");
return new OkResult();
}
You see that {Identifier}
part inside of the Blob binding? It binds to the property of the model and uses the value as the Blob’s name! So a POST with a body like this:
{
"message": "This. Is. Awesome!",
"identifier": "uniqueIdentifier"
}
… would mean you get a Blob at properties/uniqueIdentifier.txt
with the contents
Message: This. Is. Awesome!
Working example(s)
Want to get your hands on some actual working example? Go to the GitHub repo functions-triggers-bindings-example in general, or the HttpTriggerPropertyBinding file in particular for a working example on how to use property binding.
Hope this helps!