简体   繁体   English

ASP.NET 5 JSON与Azure Web App

[英]ASP.NET 5 JSON with Azure Web App

I am trying to use custom configuration for a web app that I intent to host on Azure. 我正在尝试为打算在Azure上托管的Web应用程序使用自定义配置。 The configuration should be overridable by Environment variables so that I can change it on Azure portal. 该配置应可由环境变量覆盖,以便我可以在Azure门户上对其进行更改。

I tried with following code but it does not work - details below 我尝试使用以下代码,但无法正常工作-详情如下

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

In the controller, 在控制器中

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;   
          ...
    }

The default config.json file looks like, 默认的config.json文件如下所示:

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

On Azure Portal, under app settings I have assigned value to AppSettings:Location to US and I am expecting US value in the controller. 在Azure Portal上的“应用程序设置”下,我已将“ AppSettings:Location值分配给“ US”,我希望控制器中具有“ US”的值。

Locally, in ConfigureServices I can see the value as Singapore but in the controller action Index it is null. 在本地,在ConfigureServices我可以看到值为Singapore,但在控制器操作Index中,该值为null。

Am I missing something here? 我在这里想念什么吗?

When you are reading the config.json, you need to load the section that you want to read, you need to update your code as follow: 在读取config.json时,您需要加载要阅读的部分,需要按如下方式更新代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM