代码之家  ›  专栏  ›  技术社区  ›  bdcoder

无法读取local.settings.json文件本地运行Azure函数时的文件

  •  4
  • bdcoder  · 技术社区  · 6 年前

    我试图在本地测试Azure函数时读取环境变量(使用v1.NET4.7.1)

    [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 );
         }
    
      }
    

    这个local.settings.json文件文件包含:

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

    函数编译并运行,但从不返回环境键值,日志始终包含:

     Unable to get environment key !!!!
    

    project differences

    更新:2018年9月9日 -特别感谢Karishma Tiwari,他指引了我正确的方向:

    问题是(正如karisha指出的)local.settings.json文件未将文件复制到输出路径,通过比较不工作的项目(左侧)和工作的项目(右侧)中的设置,如下所示:

    enter image description here

    解决方法:

    1. 将“Copy to Output Directory”设置更改为:“Copy if newer”

    另一点需要注意的是 MS documentation states

    "... 但我们建议您使用GetEnvironmentVariable,

    1 回复  |  直到 6 年前
        1
  •  0
  •   Karishma Tiwari - MSFT    6 年前

    我建议尝试以下方法:

    1. ConfigurationManager.AppSettings["test"] 代替System.Environment.GetEnvironment变量(“测试”)并检查是否得到预期结果。

    如果你还看到同样的问题,请告诉我。