简体   繁体   中英

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("");
    }
}

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("");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM