Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplify by using output blob binding on Azure Function

I'm triggering an Azure Function with HTTP POST and would like to save the request body to a Blob. Per the documentation this should be relatively straight forward using the output Blob storage binding. However, I was not able to get it to work. When I check the auto-generated function.json, I notice there is no binding created for the output.

The following function is working, but I would like to know what I am missing regarding the Blob output binding. How would you go about changing this to use Blob output binding?

public static class SaveSubContent
{
    [FunctionName("SaveSubContent")]
    public static IActionResult Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
        ILogger log, ExecutionContext context
        )
    {
        var config = new ConfigurationBuilder()
                        .SetBasePath(context.FunctionAppDirectory)
                        .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                        .AddEnvironmentVariables()
                        .Build();

        var connectionString = config["AzureWebJobsStorage"];

        string containerName = "france-msgs";
        string blobName = Guid.NewGuid().ToString() + ".json";


        BlobContainerClient container = new BlobContainerClient(connectionString, containerName);
        container.CreateIfNotExists();

        BlobClient blob = container.GetBlobClient(blobName);

        blob.Upload(req.Body);

        log.LogInformation("Completed Uploading: " + blobName);
        return new OkObjectResult("");
    }
}
like image 589
Matt Avatar asked Jan 28 '26 07:01

Matt


1 Answers

You can simplify this quite a bit using the output binding in conjunction with the {rand-guid} special binding expression. {rand-guid} will generate a guid for you as part of the binding, so you don't have to do it in code.

public static class Function1
{
    [FunctionName("Function1")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
        [Blob("france-msgs/{rand-guid}.json", FileAccess.ReadWrite, Connection = "AzureWebJobsStorage")] CloudBlockBlob outputBlob,
        ILogger log)
    {
        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        await outputBlob.UploadTextAsync(requestBody);

        return new OkObjectResult("");
    }
}
like image 154
Bryan Lewis Avatar answered Jan 29 '26 20:01

Bryan Lewis