I wanted to read values per environment from my MVC application and here is the code snippet:
program.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, config) =>
{
var azAppConfigSettings = config.Build();
var azAppConfigConnection = azAppConfigSettings["AppConfig"];
if (!string.IsNullOrEmpty(azAppConfigConnection))
{
// Use the connection string if it is available.
config.AddAzureAppConfiguration(options =>
{
options.Connect(azAppConfigConnection)
.Select(KeyFilter.Any, context.HostingEnvironment.EnvironmentName)
.ConfigureRefresh(refresh =>
{
// All configuration values will be refreshed if the sentinel key changes.
refresh.Register("TestApp:Settings:Sentinel", refreshAll: true);
refresh.Register("TestApp:Settings:Message").SetCacheExpiration(TimeSpan.FromDays(30));
});
});
}
else if (Uri.TryCreate(azAppConfigSettings["Endpoints:AppConfig"], UriKind.Absolute, out var endpoint))
{
// Use Azure Active Directory authentication.
// The identity of this app should be assigned 'App Configuration Data Reader' or 'App Configuration Data Owner' role in App Configuration.
// For more information, please visit https://aka.ms/vs/azure-app-configuration/concept-enable-rbac
config.AddAzureAppConfiguration(options =>
{
options.Connect(endpoint, new DefaultAzureCredential())
.ConfigureRefresh(refresh =>
{
// All configuration values will be refreshed if the sentinel key changes.
refresh.Register("TestApp:Settings:Sentinel", refreshAll: true);
});
});
}
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
ConfigController.cs
public class ConfigController : ControllerBase
{
private readonly ILogger<ConfigController> _logger;
private readonly IConfiguration _configuration;
private readonly IHostingEnvironment _hostingEnvironment;
public ConfigController(IHostingEnvironment hostingEnvironment, IConfiguration configuration, ILogger<ConfigController> logger)
{
_logger = logger;
_configuration = configuration;
_hostingEnvironment = hostingEnvironment;
}
[HttpGet]
public string Get(string key = "TestApp:Settings:Message")
{
key = key + ":" + _hostingEnvironment.EnvironmentName;
return _configuration.GetSection(key).Value.ToString();
}
}
It is always returning the value from the key that does not have a label, though EnvironmentName is set to Development and there is a matching label in Azure App Config created. Can someone help me what I am missing here please? There are three keys in Azure App Config, one without a label, one with Development and another with Production labels.