使用C#和Azure Functions 2.x将功能应用程序设置存储和加载为JSON对象

时间:2019-03-07 21:47:53

标签: azure azure-functions

下面的应用程序设置已存储并显示如下:

存储:

local.settings.json

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

已加载:

GetEnvironmentVariable("Car_Id");

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

是否可以将设置存储为对象并将其加载到对象中?

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

使用

该解决方案需要与Azure Function App设置上的设置兼容。也就是说,local.settngs.json上的设置可以保存在Azure Function应用程序设置上吗?

1 个答案:

答案 0 :(得分:0)

  

是否可以将设置存储为对象并将其加载到对象中?

,您可以使用下面的代码来实现它。

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

local.settings.json如下:

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

汽车课:

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

快照:

enter image description here

有关更多详细信息,您可以参考此article

希望它对您有帮助:)