Azure 函数:如何将 http 触发器函数的查询字符串参数绑定到 Cosmos DB 的 SQL 查询

Azure functions: how to bind query string parameters of http trigger function to SQL query of Cosmos DB

我正在尝试 运行 使用 Cosmos DB 输入绑定的 http 触发器 Azure 函数。我希望 http 触发器的 url 在查询字符串中包含几个参数,这些参数绑定到输入 Cosmos DB 绑定的 SQL 查询。我正在 function.json 中尝试以下绑定,但它不起作用(该功能甚至没有被触发):

{
  "direction": "in",
  "type": "httpTrigger",
  "authLevel": "anonymous",
  "name": "req",
  "methods": [ "get" ],
  "route": "users/{age=age?}/{gender=gender?}"
},
{
  "direction": "in",
  "type": "documentDB",
  "name": "users",
  "databaseName": "Database",
  "collectionName": "Users",
  "sqlQuery": "SELECT * FROM x where x.age = {age} and x.gender = {gender}",
  "connection": "COSMOSDB_CONNECTION_STRING"
},

根据此 answer the route constraint users/{age=age?}/{gender=gender?} is valid for Web API, and according to the documentation 您可以使用任何 Web API 路由约束和您的参数。最后,我想向看起来像 api/users?age=30&gender=male 的 Azure 函数发出 GET 请求。那应该怎么做呢?

我认为您无法配置 Cosmos DB 绑定到查询参数中定义的值,例如?age=30。至少我还没有在函数文档中看到任何类似的示例。

但是您可以将它们绑定到路由参数以获得相同的结果,您已经完成了很多工作。

保留 users/{age}/{gender} 的路由,您的 Cosmos SqlQuery 将在 http://yourfunctionhost/yourfunction/users/30/male

上调用 GET 时获取这些路由参数

GET 和 POST 参数将被绑定,因此无需任何额外配置即可在 sqlQuery 中使用它们。试一试,这在过去肯定有所改变

您可以将查询值绑定到 CosmosDB 输入绑定:
Azure Cosmos DB input binding for Azure Functions 2.x and higher

[FunctionName("DocByIdFromQueryString")]
public static IActionResult Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]
        HttpRequest req,
    [CosmosDB(
        databaseName: "ToDoItems",
        collectionName: "Items",
        ConnectionStringSetting = "CosmosDBConnection",
        Id = "{Query.id}",
        PartitionKey = "{Query.partitionKey}")] ToDoItem toDoItem,
    ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    if (toDoItem == null)
    {
        log.LogInformation($"ToDo item not found");
    }
    else
    {
        log.LogInformation($"Found ToDo item, Description={toDoItem.Description}");
    }
    return new OkResult();
}