How to add configuration values in AppSettings.json in Azure functions. Is there any structure for it?

后端 未结 7 1985
别那么骄傲
别那么骄傲 2021-02-12 18:51

What is the standard structure to add keys to appsettings.json? Also, how to read those values in our run.csx? Normally in app.config, we had Con

7条回答
  •  情歌与酒
    2021-02-12 19:15

    In Azure Functions 2.x, you need to use the .Net core configuration management style, contained in package Microsoft.Extensions.Configuration. This allows you to create a local settings.json file on your dev computer for local configuration in the Values and ConnectionString portion of the json file. The local json settings file isn't published to Azure, and instead, Azure will obtain settings from the Application Settings associated with the Function.

    In your function code, accept a parameter of type Microsoft.Azure.WebJobs.ExecutionContext context, where you can then build an IConfigurationRoot provider:

    [FunctionName("MyFunction")]
    public static async Task Run([TimerTrigger("0 */15 * * * *")]TimerInfo myTimer,
        TraceWriter log, Microsoft.Azure.WebJobs.ExecutionContext context, 
        CancellationToken ctx)
    {
       var config = new ConfigurationBuilder()
            .SetBasePath(context.FunctionAppDirectory)
            .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables()
            .Build();
    
        // This abstracts away the .json and app settings duality
        var myValue = config["MyKey"];
    
        var myConnString = config.GetConnectionString("connString");
        ... etc
    

    The AddJsonFile allows you to add a local development config file e.g. local.settings.json containing local dev values (not published)

    {
      "IsEncrypted": false,
      "Values": {
        "MyKey": "MyValue",
         ...
       },
       "ConnectionStrings": {
          "connString": "...."
    }
    

    Although seemingly using ConnectionStrings for anything other than EF seems to be discouraged

    And once deployed to Azure, you can change the values of the settings on the function Application Settings blade:

提交回复
热议问题