0

I have an azure function in .net6.0 converted from framework 4.72. My code as follows,

 [FunctionName("GetAllProducts")] 
    public static async Task<HttpResponseMessage> GetAllProducts(
        [HttpTrigger(
            AuthorizationLevel.Function, 
            "get", 
            Route = null)]HttpRequestMessage request)
    {
        try
        {
            IDocumentClient documentClient= new DocumentClient(new Uri(EndpointUrl), PrimaryKey);
            var documentsStore = new DbRepository.DocumentDBRepository<ProductsStore>(DatabaseName, documentClient, ProductsCollection);

            var queryable = documentsStore.GetQueryable();
            var result =
                await documentsStore.ExecuteQueryAsync(queryable.Where(a => a.Id == Guid.Parse(DocumentId)));

           var products = result.SelectMany(pr => pr.products).ToList();

            if (!result.Any())
            {
                return req.CreateResponse(HttpStatusCode.NotFound, $"Error: Products not found.");
            }

            return req.CreateResponse(HttpStatusCode.OK, products, "text/json");
        }
        catch (Exception ex)
        {
            return req.CreateResponse(HttpStatusCode.BadRequest, $"Failure: {ex.GetType().Name} occurred {ex.Message}");
        }
    }

The code is working when I run locally within visual studio, but when I upload it to azure it returns 500 OK response. Any ideas?

1
  • please share the code for DbRepository Commented Sep 2, 2024 at 4:44

1 Answer 1

0

I am able to get the expected response using below code.

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using System.Linq;

namespace _78932604
{
    public static class Function1
    {
        private static readonly string EndpointUrl = "https://{cosmosDBName}.documents.azure.com:443/";
        private static readonly string PrimaryKey = "yYgw*********OaEQ==";
        private static readonly string DatabaseName = "TestDB";
        private static readonly string ProductsCollection = "TestContainer";
        private static readonly string DocumentId = "b1a7b3b8-1f44-4e3f-a8f4-e4e5e4e9c3c5";

        [FunctionName("GetAllProducts")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            try
            {
                
                IDocumentClient documentClient = new DocumentClient(new Uri(EndpointUrl), PrimaryKey);
                var documentsStore = new DbRepository.DocumentDBRepository<ProductsStore>(DatabaseName, documentClient, ProductsCollection);

                var queryable = documentsStore.GetQueryable();
                var result = await documentsStore.ExecuteQueryAsync(queryable.Where(a => a.Id == Guid.Parse(DocumentId)));

                var products = result.SelectMany(pr => pr.products).ToList();

                if (!products.Any())
                {
                    return new NotFoundObjectResult("Error: Products not found.");
                }

                return new OkObjectResult(products);
            }
            catch (Exception ex)
            {
                return new BadRequestObjectResult($"Failure: {ex.GetType().Name} occurred {ex.Message}");
            }
        }
    }
}

DbRepository-

using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using Microsoft.Azure.Documents;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _78932604
{
    public class DbRepository
    {
        private readonly string databaseName;
        private readonly IDocumentClient client;

        public DbRepository(string databaseName, IDocumentClient client)
        {
            this.databaseName = databaseName;
            this.client = client;
        }

        public class DocumentDBRepository<T> where T : class
        {
            private readonly Uri collectionUri;
            private readonly IDocumentClient client;

            public DocumentDBRepository(string databaseName, IDocumentClient client, string collectionName)
            {
                this.client = client;
                this.collectionUri = UriFactory.CreateDocumentCollectionUri(databaseName, collectionName);
            }

            public IQueryable<T> GetQueryable()
            {
                return client.CreateDocumentQuery<T>(collectionUri, new FeedOptions { MaxItemCount = -1 });
            }

            public async Task<IEnumerable<T>> ExecuteQueryAsync(IQueryable<T> query)
            {
                var documentQuery = query.AsDocumentQuery();
                var results = new List<T>();

                while (documentQuery.HasMoreResults)
                {
                    var response = await documentQuery.ExecuteNextAsync<T>();
                    results.AddRange(response);
                }

                return results;
            }
        }
    }
}

I can get the output in local as well as in Function App.

enter image description here

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.