Pingpong
Pingpong

Reputation: 8009

Store and load function app settings as JSON object with C# and Azure Functions 2.x

App settings below is stored and read like below:

Stored:

local.settings.json

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "Car_Id": "id",
    "Car_Name": "name"
  }
}

Loaded:

GetEnvironmentVariable("Car_Id");

private static string GetEnvironmentVariable(string name)
    {
        return (string)System.Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Process)[name];
    }

Is it possible to store the settings as object and load it into an object?

local.settings.json

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet"
  }
  Car: {  
   "Id": "id",
   "Name": "name"
  }
}

class Car{
  public int Id {get;set;}
  public string Name {get;set;}
}

Visual studio 2017

Udpate

The solution needs to be compitable with the settings on Azure Function App settings. That is, can the settings on local.settngs.json be saved on Azure Function app settings?

Upvotes: 1

Views: 1176

Answers (1)

Joey Cai
Joey Cai

Reputation: 20067

Is it possible to store the settings as object and load it into an object?

Yes, you could use the code as below to achieve it.

  public static async Task<IActionResult> Car(
    [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "Car")]
    HttpRequest httpRequest, ILogger log, ExecutionContext context)
  {
      log.LogInformation("C# HTTP trigger function processed a request.");

      var config = new ConfigurationBuilder()
          .SetBasePath(context.FunctionAppDirectory)
          .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
          .AddEnvironmentVariables()
          .Build();
      var cars= new Car();
      config.Bind("Car", cars);
      var b = cars.Id.ToString();
      log.LogInformation($"Car id is: {b}");
      return (ActionResult)new OkObjectResult($"Hello, {b}");
  }

The local.settings.json is as below:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "xxxxx",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet"
  },
  "Car": {
    "Id": "123456",
    "Name": "name_1"
  }
}

The Car class:

public class Car
{
    public int Id { get; set; }
    public string Name { get; set; }
}

The snapshot:

enter image description here

For more details, you could refer to this article.

Hope it helps you:)

Upvotes: 1

Related Questions