What I am trying to do: I am attempting to setup Azure App Configuration with a .Net 6 web API application with a sentinel key in Azure App Configuration, with the goal of being able to change keys in azure, and none of the keys will update in my apps until the sentinel value has changed. In theory, this should allow me to safely hot swap configs.
What my issue is: When I do this IOptionsSnapshot couldn't get the value from Azure App Configuration. I am getting values are null even for the first time. When we use IConfiguration I could get the values for the first time.
Documentation I am referencing: I referred the documents from docs.microsoft
-
Pls refer to my code sample, it worked in my side. I created a new .net 6 api project. After running the app, you can change the value in azure portal fot testing the refresh.
Add connection string to appsetting.json:
"ConnectionStrings": { "AppConfig": "Endpoint=https://xxxx.azconfig.io;Id=yaFxxSgH;Secret=5MYxxxs=" }
My program.cs, pls don't forget to add service and middleware, the middleware is used to monitors the sentinel key.
using WebApiNet6AzureAppConfig.Models; var builder = WebApplication.CreateBuilder(args); ConfigurationManager configuration = builder.Configuration; var connectionString = builder.Configuration.GetConnectionString("AppConfig"); builder.Host.ConfigureAppConfiguration((hostingContext, config) => { var settings = config.Build(); config.AddAzureAppConfiguration(options => { options.Connect(connectionString) .ConfigureRefresh(refresh => { refresh.Register("TestApp:Settings:FontColor", refreshAll: true) .SetCacheExpiration(new TimeSpan(0, 0, 30)); }); }); }).ConfigureServices(services => { services.AddControllers(); }); builder.Services.Configure<AppSettings>(configuration.GetSection("TestApp:Settings")); builder.Services.AddAzureAppConfiguration(); builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseAzureAppConfiguration(); app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
My test api:
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using WebApiNet6AzureAppConfig.Models; namespace WebApiNet6AzureAppConfig.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private readonly AppSettings _settings; public WeatherForecastController(IOptionsSnapshot<AppSettings> settings) { _settings = settings.Value; } [HttpGet(Name = "GetWeatherForecast")] public string Get() { var res = _settings.Message; return res; } } }