Mark Chidlow
Mark Chidlow

Reputation: 1472

How to access local appsettings in Azure Function

I'm really struggling to find how to access the App Settings from an instance created in an Azure Function.

I have the following code...

namespace ThingServiceFunctionApp
{    
    public static class RoleFunctions
    {
        [FunctionName("GetThings")]
        public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "roles")]HttpRequest req, ILogger log)
        {
            return await FunctionApp.GetFunction<IGetThingsFunction>().RunAsync(req, log).ConfigureAwait(false);
        }


    public static class FunctionApp
    {
        private static readonly IFunctionFactory FuncFactory = new FunctionFactory(new Startup());

        public static IFunction GetFunction<TFunction>() where TFunction : IFunction
        {
            return FuncFactory.Create<TFunction>();
        }
    }


     public class Startup : IStartup
     {

          private IConfiguration Configuration { get; }

          public Startup()
          {
              Configuration = new ConfigurationBuilder()
                  .SetBasePath(Directory.GetCurrentDirectory())
                  .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                  .AddEnvironmentVariables()
                  .Build();
          }


          public IServiceCollection ConfigureServices(IServiceCollection services)
          {
              services
                  .AddSingleton<IThingService, ThingService>()
                  .AddTransient<IGetThingsFunction, GetThings>();

              return services;
          } 
        }
      }
  }

How can I access values from Configuration from within the ThingService or GetThings function?

Not relevant but FYI I have added my own support for DI (code not shown) - hence the .AddSingleton etc.

Thanks!

Upvotes: 1

Views: 2017

Answers (2)

Lee Liu
Lee Liu

Reputation: 2091

To access local appsettings in Azure Function(Whether it's on Azure or local debugging.), we can do as below:

public static string GetEnvironmentVariable(string name)
{
    return name + ": " +
        System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
}

More information for your reference: Environment variables

Upvotes: 1

aframestor
aframestor

Reputation: 196

In our project we added the variables from the local config file to Application Settings in the Azure Portal.

Create the object like so: new ConfigurationBuilder().AddEnvironmentVariables().Build();

And then you retrieve them as usual i.e. Configuration["Key"];

Upvotes: 1

Related Questions