0

I created an Azure function project in VS Code, using .NET 8 isolated. I followed the instructions here Develop Azure Functions by using Visual Studio Code and once I finished and deployed it, the basic function scaffolding worked. So I implemented access to a table in Azure storage.

My program.cs file is like this - the DependencyInjection package is not used:

using Microsoft.Azure.Functions.Worker.Builder;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

var builder = FunctionsApplication.CreateBuilder(args);

// Agregar configuración de variables de entorno
builder.Configuration
    .AddEnvironmentVariables() // Agrega variables de entorno
    .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true); // Para entornos locales

// Configurar servicios adicionales (si es necesario)
// builder.Services.AddTransient<IMyService, MyServiceImplementation>();

builder.ConfigureFunctionsWebApplication();

// Application Insights isn't enabled by default. See https://aka.ms/AAt8mw4.
// builder.Services
//     .AddApplicationInsightsTelemetryWorkerService()
//     .ConfigureFunctionsApplicationInsights();

builder.Build().Run();

And this is my local.settings.json:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=false",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
    "TableStorageConnection": "azure-storage-connectionString",
    "HelloWho": "Jon Doe Who"
  },
  "Host": {
    "CORS": "*"
  }
}

I created a very simple function called GetWho to try and read the connection string, because at some point, my function was not reading it and I got this in a log.

2024-11-26T02:15:50.309 [Information] Executing 'Functions.GetCities' (Reason='This function was programmatically called via the host APIs.', Id=67fcf38f-daa0-4433-9c54-f75331cd4dbc)
2024-11-26T02:15:50.657 [Information] Retrieving cities with registered open mics
2024-11-26T02:15:50.734 [Error] Function 'GetCities', Invocation id '67fcf38f-daa0-4433-9c54-f75331cd4dbc': An exception was thrown by the invocation.
Microsoft.Azure.WebJobs.Script.Workers.Rpc.RpcException : Result: Function 'GetCities', Invocation id '67fcf38f-daa0-4433-9c54-f75331cd4dbc': An exception was thrown by the invocation.
Exception: System.ArgumentException: Value cannot be an empty string. (Parameter 'connectionString')

This is the GetWho method's code:

public class GetWho
{
    private readonly ILogger<GetWho> _logger;
    private readonly IConfiguration _configuration;

    public GetWho(ILogger<GetWho> logger, IConfiguration configuration)
    {
        _logger = logger;
        _configuration = configuration;
    }

    [Function("GetWho")]
    public IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequest req)
    {
        _logger.LogInformation("C# HTTP trigger function processed a request.");
        return new OkObjectResult($"Welcome to Azure Functions! {_configuration["HelloWho"]}");
    }
}

Up here, all my functions are working ok on localhost. I get the values of the variables and GetCities returns the list I expect. The function is connected directly to Azure Storage, I am not using a local storage.

Once I deploy the function. It looks like it was deployed successfully, and I can see the functions listed in the App Services in Azure, but once I want to test run them, I get errors, but no logs or explicit error message. And the same thing happens when I click on "Get Function URL".

Error while loading. Ask questions and use troubleshooting tools to investigate these errors. Diagnose and solve problems. Encountered an error (InternalServerError) from host runtime.

Curiously, there are no invocations recorded.

The invocations page of the function showing no invocations.

Another way of doing the program.cs I tried, was this. Same result. The DependencyInjection package is not used

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;

namespace el_open_api
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = new HostBuilder()
            .ConfigureAppConfiguration((context, config) =>
            {
                config.Sources.Clear();
                config.AddEnvironmentVariables();
            })
            .ConfigureFunctionsWebApplication()
            .ConfigureFunctionsWorkerDefaults()
            .Build();

            host.Run();
        }
    }
}

I run out of talent at this point and can't get this to work. Any help is appreciated.

4
  • Looking at the line var builder = FunctionsApplication.CreateBuilder(args); I have always used var builder = new HostBuilder() instead, as per this: learn.microsoft.com/en-us/azure/azure-functions/… . It might not be relevant but can you try that instead? Also I struggled to find what your line actually does; the only reference seems to be for a .NET Aspire project rather than a conventional Functions project. Commented Nov 26, 2024 at 23:08
  • Thank you @Andrew, At the end of the post I put the code you suggested. I also tried that with no result. I created the project using the Create Azure function project in vscode. The purpose is just to get some info out of a table. It is working ok locally. Commented Nov 27, 2024 at 1:21
  • Did the below answer helped @RickerSilva or you have any other query? Commented Nov 28, 2024 at 3:19
  • It turns out the run/test option in Azure portal is very limited. It doesn't run code that rely on more things than a basic hello world and it won't run it. Out of desperation, I just send a request with the browser using the known format of azure function url and the api is working ok. Commented Nov 28, 2024 at 15:31

1 Answer 1

0

Exception: System.ArgumentException: Value cannot be an empty string. (Parameter 'connectionString')

This clearly says that connection string is missing. This is a known issue with Function app that whenever you deploy the function to azure. You also need to add the local setting values to azure function app's environment variables section, then only it will work Below code worked for me :

Function.cs:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace FunctionApp13
{
    public class Function1
    {
        private readonly ILogger<Function1> _logger;
        private readonly IConfiguration ri_cng;

        public Function1(ILogger<Function1> logger,IConfiguration configuration)
        {
            _logger = logger;
            ri_cng = configuration;
        }

        [Function("Function1")]
        public IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequest req)
        {
            _logger.LogInformation("C# HTTP trigger function processed a request.");
            var rii = ri_cng["TableStorageConnection"]; 
            return new OkObjectResult($"Welcome to Azure Functions! {ri_cng["rith_cho"]},{rii}");
        }
    }
}

Program.cs:

using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var rith = new HostBuilder()
    .ConfigureFunctionsWebApplication()
    .ConfigureAppConfiguration((context, config) =>
    {
        config.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
              .AddEnvironmentVariables();
    })
    .ConfigureServices(cho =>
    {      
    })

    .Build();

rith.Run();

local.settings.json:

{
    "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
    "TableStorageConnection": "azure-storage-connectionString",
    "rith_cho": "Rithwik Bojja"
  }
}

Deployed to Function app:

enter image description here

In Environment Variables section add:

make sure to add connection and other variables:

enter image description here

enter image description here

After apply click on save :

enter image description here

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" />
    <!-- Application Insights isn't enabled by default. See https://aka.ms/AAt8mw4. -->
    <!-- <PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.22.0" /> -->
    <!-- <PackageReference Include="Microsoft.Azure.Functions.Worker.ApplicationInsights" Version="2.0.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>

Output:

enter image description here

So use above code and deploy and check, if still it does not work create a new project use my code completely as it works, later make changes in that.

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.