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