AndyW
AndyW

Reputation: 453

Configuring Azure Function Cosmos DB output

I have an Azure V4 function written in C# that has an HTTP input trigger and a multiple output binding (HttpResponse & Aure CosmosDB).

It is running fine when I run it locally and connect to the Cosmos DB Emulator, and is published to Azure and running.

The issue that I am trying to resolve is in getting it to connect to my Azure instance of Cosmos DB.

When I open the Integration Page in the Azure portal (click on function name, within the function app, then click integration) and click Azure Cosmos DB from the Outputs screen, I can see all of the settings filled in except 'Cosmos DB Account Connection' which has the text 'No Existing Connections Available'.

On my output binding I have 'connection = "myConnectionString" set and I have this defined in the function app settings (Environment Variables).

I can't find any documentation on how to set this value, so is wondering if anyone has an idea. What I think I am expecting to see is "myConnectionString" displayed in the 'Cosmos DB Account Connection' field.

Upvotes: 0

Views: 65

Answers (1)

RithwikBojja
RithwikBojja

Reputation: 11383

I have tried below approach which worked for me as expected:

Function1.cs:

using System.Net;
using System.Text.Json;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;

namespace FunctionApp9
{
    public class Function1
    {
        private readonly ILogger<Function1> ri_lg;

        public Function1(ILogger<Function1> logger)
        {
            ri_lg = logger;
        }

        [Function("Function1")]
        public async Task<RithRes> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestData req)
        {
            ri_lg.LogInformation("Hello Rithwik, Function Execution started");
            var ric_doc = new Rith_Data
            {
                Id = "8008",
                Message = "Rithwik"
            };
            var ri_res = req.CreateResponse(HttpStatusCode.OK);
            return new RithRes { Response = ri_res, Document = ric_doc };
        }
    }

    public class RithRes
    {
        [HttpResult]
        public required HttpResponseData Response { get; set; }

        [CosmosDBOutput(databaseName : "Testdb", containerName:" testcon", Connection = "rithconst", CreateIfNotExists = true, PartitionKey = "/id")]
        public Rith_Data? Document { get; set; }
    }

    public class Rith_Data
    {
        public string? Id { get; set; }
        public string? Message { get; set; }
    }
}

local.settings.json:

{
    "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
    "rithconst": "AccountEndpoint=https://test0209.documents.azure.com:443/;AccountKey=g5rithwikbojjanA==;"
  }
}

Program.cs:

using Microsoft.Extensions.Hosting;
using Microsoft.Azure.Functions.Worker;
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using Azure.Core.Serialization;

var ribo = new HostBuilder()
    .ConfigureFunctionsWebApplication()
    .ConfigureServices(boj =>
    {
        boj.Configure<WorkerOptions>(ch =>
        {
            ch.Serializer = new JsonObjectSerializer(
                new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                    DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull
                });
        });
    })
    .Build();

ribo.Run();

csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <AzureFunctionsVersion>v4</AzureFunctionsVersion>
    <OutputType>Exe</OutputType>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
      <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.CosmosDB" Version="4.12.0" />
      <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="2.0.0" />
      <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.2.0" />
      <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore" Version="2.0.0" />
      <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="2.0.0" />
  </ItemGroup>
  <ItemGroup>
    <None Update="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </None>
  </ItemGroup>
  <ItemGroup>
    <Using Include="System.Threading.ExecutionContext" Alias="ExecutionContext" />
  </ItemGroup>
</Project>

After Deploying, I have added connection string rithconst which is same name as in code and in local.settings.json:

enter image description here

then it shows like this:

enter image description here

Output:

After invoking :

enter image description here

enter image description here

Upvotes: 1

Related Questions