Search code examples
azure-functions

Unable to read local.settings.json file when running Azure Function locally


I am trying to read an environment variable while testing Azure Functions locally (using v1 .Net 4.7.1)

Below is the function code:

[FunctionName( "test" )]
  public static async Task<HttpResponseMessage> Run( [HttpTrigger( AuthorizationLevel.Anonymous, "post", Route = null )]HttpRequestMessage req, TraceWriter log )
  {

     String s;

     log.Info( "test: Begin..." );

     s = System.Environment.GetEnvironmentVariable( "test" );

     if ( String.IsNullOrEmpty( s ) )
     {
        log.Info( "Unable to get environment key !!!!" );
     }
     else
     {
        log.Info( "Key value = " + s );
     }

  }

The local.settings.json file contains:

{
"IsEncrypted": false,
"Values": {
   "AzureWebJobsStorage": "UseDevelopmentStorage=true",
   "AzureWebJobsDashboard": "UseDevelopmentStorage=true",
   "test": "test_value"
   }
}

The function compiles and runs, but the environment key value is never returned, the log always contains:

 Unable to get environment key !!!!

The weird part is I have another project (same code as above) and it works just fine. The only difference in the assemblies is the Microsoft.Net.Sdk.Functions DLL (1.0.19) vs (1.0.13) -- the current project (that does NOT work) is using 1.0.19 -- so I downgraded to 1.0.13 -- but it made NO DIFFERENCE !

project differences

UPDATE: 9-Sep-2018 - special thanks to Karishma Tiwari who steered me in the right direction:

The problem was (as Karismha pointed out) that the local.settings.json file was NOT being copied to the output path, as shown below by comparing the settings in the project that is NOT working (on left), and the project that is working (right):

enter image description here

To solve:

  1. Right-click on local.settings.json -> Properties
  2. Change the "Copy to Output Directory" setting to: "Copy if newer"

One other point to note is that MS documentation states states:

"... but we recommend that you use GetEnvironmentVariable ...",

Problem solved.


Solution

  • I would recommend trying the following:

    1. First of all, try using ConfigurationManager.AppSettings["test"] in place of System.Environment.GetEnvironmentVariable( "test" ) and check if you are getting the expected result.

    2. Make sure your local.settings.json file is marked to always be copied to the build output. (by right clicking on it in Visual studio). This will copy your files to the output path similar to bin\debug..

    Let me know if you are still seeing the same issue.