Home > Back-end >  Microsoft.Azure.WebJobs.Host: Error indexing method 'HttpExample'
Microsoft.Azure.WebJobs.Host: Error indexing method 'HttpExample'

Time:09-27

When running my Azure Functions App I'm getting the following error:

Microsoft.Azure.WebJobs.Host: Error indexing method 'HttpExample'. Microsoft.Azure.WebJobs.Host: Can't bind CosmosDB to type 'Microsoft.Azure.Documents.Client.DocumentClient'.

This is my Run() function in Function1.cs file:

        public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "policy")] HttpRequest req,
        [CosmosDB(Connection = "CosmosConnectionString")] DocumentClient cosmos,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        
        var query = "SELECT * FROM Policy";
        
        var policies = GetDocumentsByQuery(
           cosmos,
           "AR",
           "Policy",
           query).ToList();

        return new OkObjectResult(policies);
    }

I pass my CosmosConnectionString as a user secret. I'm using Azure Functions v4 with CosmosDB v4 preview and .NET Core 6. I am out of ideas why I'm getting this error. I worked previously with .NET Core 3.1 and earlier version of Azure functions CosmosDB and it worked fine.

EDIT:

public static IQueryable<dynamic> GetDocumentsByQuery(DocumentClient cosmos, string database, string collection, string query, string partitionKey = null)
    {
        try
        {
            FeedOptions feedOptions;
            if (partitionKey == null)
            {
                feedOptions = new FeedOptions { EnableCrossPartitionQuery = true, PopulateQueryMetrics = true };
            }
            else
            {
                feedOptions = new FeedOptions { PartitionKey = new PartitionKey(partitionKey), PopulateQueryMetrics = true };
            }

            var documentQuery =
            cosmos.CreateDocumentQuery(
                UriFactory.CreateDocumentCollectionUri(database, collection),
                query,
                feedOptions);

            return documentQuery;
        }
        catch (Exception)
        {
            throw;
        }
    }

CodePudding user response:

Looks like you're binding against the wrong type:

Can't bind CosmosDB to type 'Microsoft.Azure.Documents.Client.DocumentClient'

For 4.x, use CosmosClient. Taken from HTTP trigger, get multiple docs, using CosmosClient

The following example shows a C# function that retrieves a list of documents. The function is triggered by an HTTP request. The code uses a CosmosClient instance provided by the Azure Cosmos DB binding, available in extension version 4.x, to read a list of documents. The CosmosClient instance could also be used for write operations.

using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Cosmos;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;

namespace CosmosDBSamplesV2
{
    public static class DocsByUsingCosmosClient
    {  
        [FunctionName("DocsByUsingCosmosClient")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post",
                Route = null)]HttpRequest req,
            [CosmosDB(
                databaseName: "ToDoItems",
                containerName: "Items",
                Connection = "CosmosDBConnection")] CosmosClient client,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            var searchterm = req.Query["searchterm"].ToString();
            if (string.IsNullOrWhiteSpace(searchterm))
            {
                return (ActionResult)new NotFoundResult();
            }

            Container container = client.GetDatabase("ToDoItems").GetContainer("Items");

            log.LogInformation($"Searching for: {searchterm}");

            QueryDefinition queryDefinition = new QueryDefinition(
                "SELECT * FROM items i WHERE CONTAINS(i.Description, @searchterm)")
                .WithParameter("@searchterm", searchterm);
            using (FeedIterator<ToDoItem> resultSet = container.GetItemQueryIterator<ToDoItem>(queryDefinition))
            {
                while (resultSet.HasMoreResults)
                {
                    FeedResponse<ToDoItem> response = await resultSet.ReadNextAsync();
                    ToDoItem item = response.First();
                    log.LogInformation(item.Description);
                }
            }

            return new OkResult();
        }
    }
}
  • Related