【问题标题】:Azure functions: how to bind query string parameters of http trigger function to SQL query of Cosmos DBAzure 函数:如何将 http 触发器函数的查询字符串参数绑定到 Cosmos DB 的 SQL 查询
【发布时间】:2018-01-28 18:42:45
【问题描述】:

我正在尝试使用 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,路由约束users/{age=age?}/{gender=gender?} 对Web API 有效,并且根据documentation您可以使用任何Web API 路由约束与您的参数。最终,我想向 Azure 函数发出一个类似于 api/users?age=30&gender=male 的 GET 请求。那应该怎么做呢?

【问题讨论】:

    标签: azure azure-functions azure-cosmosdb azure-functions-runtime


    【解决方案1】:

    您可以将查询值绑定到 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();
    }
    

    【讨论】:

      【解决方案2】:

      GET 和 POST 参数将被绑定,因此它们可以在 sqlQuery 内部使用,无需任何额外配置。试试看,这在过去肯定改变了

      【讨论】:

        【解决方案3】:

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

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

        保持users/{age}/{gender} 的路由,然后您的 Cosmos SqlQuery 将在对http://yourfunctionhost/yourfunction/users/30/male 调用 GET 时获取这些路由参数

        【讨论】:

        • 我担心会是这种情况,因为我也找不到任何绑定到查询字符串中的参数的示例。感谢您的确认。
        • 不正确的 GET 参数将被绑定,它们可以在 sqlQuery 中使用。也许这在过去发生了变化
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-23
        • 2012-01-05
        • 2019-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多