ASP.NET 5 JSON 使用 Azure Web 应用程序

ASP.NET 5 JSON with Azure Web App

我正在尝试为我打算在 Azure 上托管的 Web 应用程序使用自定义配置。配置应该可以被环境变量覆盖,这样我就可以在 Azure 门户上更改它。

我尝试使用以下代码,但它不起作用 - 详情如下

   public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
   {
      var builder = new ConfigurationBuilder()
                        .AddJsonFile("config.json", optional:true)
                        .AddEnvironmentVariables();
      Configuration = builder.Build();            
   }

   public IConfigurationRoot Configuration { get; set; }

   public void ConfigureServices(IServiceCollection services)
   {
      services.AddOptions(); 
      services.Configure<AppSettings>(Configuration);
   }

在控制器中,

public class HomeController : Controller
{
    private IOptions<AppSettings> Configuration;

    public HomeController(IOptions<AppSettings> configuration)
    {
        Configuration = configuration;
    }

    public async Task<IActionResult> Index()
    {
          string location = Configuration.Value.Location;   
          ...
    }

默认的 config.json 文件看起来像,

{
  "AppSettings": {
    "Location" : "Singapore"
  }
}

在 Azure 门户上,在应用程序设置下,我已将 AppSettings:Location 的值分配给 US,我希望在控制器中使用 US 值。

在本地,在 ConfigureServices 中我可以看到值为新加坡,但在控制器操作索引中它为空。

我是不是遗漏了什么?

当您阅读config.json时,您需要加载您想要阅读的部分,您需要更新您的代码如下:

public void ConfigureServices(IServiceCollection services)
{
    services.AddOptions();
    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}