15

I am trying to retrieve a custom setting from local.settings.json file. Example I am trying to read tables list present in the below local.settings.json file

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "AzureWebJobsDashboard": "UseDevelopmentStorage=true",
    "TableList": "TestTableName1,TestTableName2"
  }
}

Using the following code am reading it

string tableslist = ConfigurationManager.AppSettings["TableList"];

and it works, but I've read in a few places that this works only when debugging locally, it might not work after it is deployed, in production environment. Could someone point me how to do this in the right way? Or the problem is only applicable to the connection string related settings?

8
  • You should manually specify these values at Azure Portal via Application Settings, because local.settings.json is not published. Commented Aug 10, 2018 at 7:40
  • 1
    @SlavaUtesinov - So while developing, whatever settings we make in local.settings.json file, has to be separately applied in Azure Portal via Application Settings, is that right Commented Aug 10, 2018 at 7:43
  • Yes, this file is used only at development Commented Aug 10, 2018 at 7:45
  • 1
    should not try to maintain or modify project code, not settings Commented Aug 10, 2018 at 7:48
  • 2
    @KirkLarkin - Yep, that's exactly my problem. So as Slava confirmed, we need to manually update the application settings. Commented Aug 10, 2018 at 7:52

3 Answers 3

26

@Kirk and @Slava have helped you get rid of confusion. Just add some details for you to refer.

By default, publication neither upload local.settings.json to Azure, nor makes modification on Application settings based on that local file, hence we need to update them manually on Azure portal. We can also do that on VS publish panel.(Create profile first if we need to change settings before publish.)

enter image description here

About how to get parameters in app settings, one thing to note is that ConfigurationManager is no long supported in v2 function(runtime beta), may only get null or exception with it. For v1 function(runtime ~1), it still works.

  1. For v1 function

    To read Application settings on Azure(also Values in local.settings.json), System.Environment.GetEnvironmentVariable($"{parameterName}") is recommended.

    Turn to Connection strings, unfortunately GetEnvironmentVariable only works on Azure because Connection strings(ConnectionStrings in local.settings.json) are not imported into Environment Variables. So we need ConfigurationManager, which works in both Azure and local env. Of course it can read Application settings as well.

  2. For v2 function, two choices for both Application settings and Connection strings.

    One is to use GetEnvironmentVariable. We can refer to this list for Prefixes of Connection String on Azure.

    // Get Application settings
    var appParameter= "AzureWebJobsStorage";
    System.Environment.GetEnvironmentVariable($"{appParameter}");
    
    // Get Connection strings(put local and Azure env together)
    var connParameter= "MySqlAzureConnection";
    var Prefix = "SQLAZURECONNSTR_";
    var connectionString = System.Environment.GetEnvironmentVariable($"ConnectionStrings:{connParameter}");
    if(string.IsNullOrEmpty(connectionString )){
       connectionString = System.Environment.GetEnvironmentVariable($"{Prefix}{connParameter}");
    }
    

    Another one is to use ConfigurationBuilder. Add ExecutionContext parameter, which is used to locate function app directory.

    [FunctionName("FunctionName")]
    public static void Run(...,ExecutionContext context)
    {
       //"Values" and "Connection" sections are injected into EnvironmentVariables automatically hence we don't need to load Json file again. 
       //Hence SetBasePath and AddJsonFile are only necessary if you have some custom settings(e.g. nested Json rather than key-value pairs) outside those two sections. It's recommended to put those setting to another file if we need to publish them.
       //Note that Function binding settings(e.g. Storage Connection String) must be EnvironmentVariables, i.e. must be stored in "Values" section.
        var config = new ConfigurationBuilder()
            .SetBasePath(context.FunctionAppDirectory)
            .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables()
            .Build();
    
        // Get Application Settings
        var appParameter= "AzureWebJobsStorage";
        string appsetting = config[$"{appParameter}"];
    
        // Get Connection strings
        var connParameter= "MySqlAzureConnection";
        string connectionString = config.GetConnectionString($"{connParameter}");
    }
    
Sign up to request clarification or add additional context in comments.

5 Comments

Environment.GetEnvironmentVariable("ConnectionStrings:{ParameterName}") is getting the connection string. Am getting NULL as result
@Pரதீப் Have updated my answer, sorry for the waste of your time.
ConfigurationBuilder does this work on both v1 and v2 ?
@Pரதீப் Not on v1 based on my knowing. If you try it in v1 which targets at .netframework, you may find no definition for AddEnvironmentVariables() as ConfigurationBuilder is on .netstandard2.0. There may be more work to do if we want achieve the compatibility between code depending on .netframwork and .netstandard, you don't need to think about the further support for v2 too early as v1 still has a long time to live for production use before v2 become GA.
2

When using Environment.GetEnvironmentVariable in an .Net Core Azure Function I had to add the EnvironmentVariableTarget.Process parameter to retrieve the connection string

 string connectionString= Environment.GetEnvironmentVariable("DBConnectionString", 
 EnvironmentVariableTarget.Process);

My local.settings.json looked something like this:

 {"IsEncrypted": false,
 "Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"DBConnectionString": "<conn string here>"
 }
}

2 Comments

I also configured the connection string in the Azure portal for online deployment as explained above. To work locally from within Visual Studio 2019 I had to make the above changes to retrieve the connection string for local debugging.
Except for the fact that the first line in GetEnvironementVariable is if (target == EnvironmentVariableTarget.Process) return GetEnvironmentVariable(variable); So using the overload with the Process parameter seems hardly to be of any value and cannot have solved your problem.
2

For those who are trying to use the EnvironmentVariable in the Functions Startup, And find the Environment null, You can check this code:

using System.IO;
using System.Net;
using System.Net.Mail;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;

[assembly: FunctionsStartup(typeof(Startup))]
namespace Company.Domain.Project;

internal class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        var configBuilder = new ConfigurationBuilder()
            .AddEnvironmentVariables();
        
        IConfiguration configuration = configBuilder.Build();
        builder.Services.AddSingleton(configuration);
    }
}


after that you can use IConfiguration.GetValue<TType>("key"); in your startup and configuration.

The full described guidance can be found here:

quickstart azure functions - Microsoft Documentation

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.