Skip to end of metadata
Go to start of metadata

You are viewing an old version of this content. View the current version.

Compare with Current View Version History

« Previous Version 2 Next »

Azure Cosmos DB

To use Azure Cosmos DB in serverless mode, choose Serverless as the Capacity mode when creating your account.

1.Register binding extensions

dotnet add package Microsoft.Azure.WebJobs.Extensions.CosmosDB --version 3.0.10

2.Add an output binding

[CosmosDB(databaseName: "my-database", collectionName: "my-container",
    ConnectionStringSetting = "CosmosDbConnectionString"
    )]IAsyncCollector<dynamic> documentsOut,

3.Add code that uses the output binding

[FunctionName("HttpExample")]
public static async Task<IActionResult> Run(HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
    [CosmosDB(
        databaseName: "my-database",
        collectionName: "my-container",
        ConnectionStringSetting = "CosmosDbConnectionString")]IAsyncCollector<dynamic> documentsOut,
    ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");
    string name = req.Query["name"];

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;

    if (!string.IsNullOrEmpty(name))
    {
        // Add a JSON document to the output container.
        await documentsOut.AddAsync(new
        {
            // create a random ID
            id = System.Guid.NewGuid().ToString(),
            name = name
        });
    }
    string responseMessage = string.IsNullOrEmpty(name)
        ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
        : $"Hello, {name}. This HTTP triggered function executed successfully.";

    return new OkObjectResult(responseMessage);
}

Azure SQL

  • No labels