我正在嘗試做的事情:我正在嘗試使用 .Net 6 Web API 應用程式在 Azure 應用程式配置中使用哨兵密鑰設定 Azure 應用程式配置,目標是能夠在 azure 中更改密鑰,并且所有密鑰都不會在我的應用程式中更新,直到哨兵值發生變化。理論上,這應該允許我安全地熱交換配置。
我的問題是:當我這樣做時,IOptionsSnapshot 無法從 Azure 應用程式配置中獲取值。即使是第一次,我也得到了 null 值。當我們使用 IConfiguration 時,我可以第一次獲得這些值。
我參考的檔案:我參考了 docs.microsoft 的檔案
請參考我的代碼示例,它在我身邊有效。我創建了一個新的 .net 6 api 專案。運行應用程式后,您可以更改 Azure 門戶中的值以測驗重繪 。

將連接字串添加到 appsetting.json:
"ConnectionStrings": { "AppConfig": "Endpoint=https://xxxx.azconfig.io;Id=yaFxxSgH;Secret=5MYxxxs=" }我的program.cs,請不要忘記添加服務和中間件,中間件是用來監控哨兵鍵的。
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();我的測驗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; } } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/431759.html
