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

标签 asp.net azure asp.net-core azure-web-app-service

我正在尝试对打算在 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);
   }

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

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

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

在 Azure 门户上,在应用程序设置下,我已将 AppSettings:Location 的值分配给 US,并且我期望 Controller 中的 US 值。

在本地,在 ConfigureServices 中,我可以看到该值为 Singapore,但在 Controller 操作 Index 中它为 null。

我在这里遗漏了什么吗?

最佳答案

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

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

关于ASP.NET 5 JSON 与 Azure Web 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34517723/

相关文章:

azure - 审核特定 Azure SQL Server 数据库用户

c# - 如何在 Razor Pages 中动态生成文件以供下载

c# - EF - 嵌套包含抛出错误

javascript - react 自定义组件(数据表)

c# - 根据 asp GridView 列中的值显示图像

c# - 如何在jquery中独立于浏览器捕获精确的td值

asp.net - itextsharp 不关闭文件

html - 与文本内嵌的按钮图像

.net - Azure Functions 主机运行配置 - 运行所有函数

Azure Web 部署任务失败 - 存在未闭合的文字字符串