如何立即更新 .NET Core 3.1 的配置文件以实现高效配置管理?

摘要:``` public class Startup { private ConfigurationReloadToken _changeToken = new ConfigurationReloadToken(); private byte[
public class Startup { private ConfigurationReloadToken _changeToken = new ConfigurationReloadToken(); private byte[] _configFileHash = new byte[20]; public Startup(IConfiguration configuration) { Configuration = configuration; } public void ConfigureServices(IServiceCollection services) { ... } public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IConfiguration config) { ChangeToken.OnChange( () => config.GetReloadToken(), () => { byte[] configFileHash = ComputeHash("appSettings.json"); if (!_configFileHash.SequenceEqual(configFileHash)) { Log.Information("Configuration changed"); _configFileHash = configFileHash; } var previousToken = Interlocked.Exchange(ref _changeToken, new ConfigurationReloadToken()); previousToken.OnReload(); }); } private byte[] ComputeHash(string file) { if (File.Exists(file)) { using (var fs = File.OpenRead(file)) { return System.Security.Cryptography.SHA1.Create().ComputeHash(fs); } } else { return new byte[20]; } } }