我正在使用IOptions
模式,如in the official documentation所述。如何将值更新到appsetting.json?
这项工作正常,当我读取appsetting.json
的值时,但是如何更新值并将更改保存回appsetting.json
?
在我的情况下,我有几个可以从用户界面编辑的字段(由管理员用户在应用程序中)。因此,我正在寻找通过选项访问器来更新这些值的理想方法。
我正在使用IOptions
模式,如in the official documentation所述。如何将值更新到appsetting.json?
这项工作正常,当我读取appsetting.json
的值时,但是如何更新值并将更改保存回appsetting.json
?
在我的情况下,我有几个可以从用户界面编辑的字段(由管理员用户在应用程序中)。因此,我正在寻找通过选项访问器来更新这些值的理想方法。
在撰写本答案时,似乎没有Microsoft.Extensions.Options
软件包提供的组件提供将配置值写回appsettings.json
的功能。
在我ASP.NET Core
项目之一,我希望能够让用户改变一些应用程序设置 - 和这些设定值应存放在appsettings.json
,更precisly在可选appsettings.custom.json
文件,如果存在的话是被添加到配置。
就像这个...
public Startup(IHostingEnvironment env)
{
IConfigurationBuilder builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile("appsettings.custom.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
this.Configuration = builder.Build();
}
我宣布IWritableOptions<T>
接口扩展IOptions<T>
;所以只要我想读取和写入设置,我就可以用IWritableOptions<T>
代替IOptions<T>
。
public interface IWritableOptions<out T> : IOptions<T> where T : class, new()
{
void Update(Action<T> applyChanges);
}
另外,我想出了IOptionsWriter
,这是旨在由IWritableOptions<T>
被用于更新的结构部分的组分。这是我实现的beforementioned接口...
class OptionsWriter : IOptionsWriter
{
private readonly IHostingEnvironment environment;
private readonly IConfigurationRoot configuration;
private readonly string file;
public OptionsWriter(
IHostingEnvironment environment,
IConfigurationRoot configuration,
string file)
{
this.environment = environment;
this.configuration = configuration;
this.file = file;
}
public void UpdateOptions(Action<JObject> callback, bool reload = true)
{
IFileProvider fileProvider = this.environment.ContentRootFileProvider;
IFileInfo fi = fileProvider.GetFileInfo(this.file);
JObject config = fileProvider.ReadJsonFileAsObject(fi);
callback(config);
using (var stream = File.OpenWrite(fi.PhysicalPath))
{
stream.SetLength(0);
config.WriteTo(stream);
}
this.configuration.Reload();
}
}
由于笔者不知道有关文件的结构,我决定处理的部分作为JObject
对象。如果当前值为null
,访问器将尝试查找所请求的段并将其反序列化为T
的实例,使用当前值(如果找不到)或仅创建一个新实例T
。该持有者对象将传递给调用者,调用者将对其应用更改。比变化的目标被转换回JToken
实例,它是要替代部分...
class WritableOptions<T> : IWritableOptions<T> where T : class, new()
{
private readonly string sectionName;
private readonly IOptionsWriter writer;
private readonly IOptionsMonitor<T> options;
public WritableOptions(
string sectionName,
IOptionsWriter writer,
IOptionsMonitor<T> options)
{
this.sectionName = sectionName;
this.writer = writer;
this.options = options;
}
public T Value => this.options.CurrentValue;
public void Update(Action<T> applyChanges)
{
this.writer.UpdateOptions(opt =>
{
JToken section;
T sectionObject = opt.TryGetValue(this.sectionName, out section) ?
JsonConvert.DeserializeObject<T>(section.ToString()) :
this.options.CurrentValue ?? new T();
applyChanges(sectionObject);
string json = JsonConvert.SerializeObject(sectionObject);
opt[this.sectionName] = JObject.Parse(json);
});
}
}
最后,我实现了一个扩展方法IServicesCollection
让我轻松地配置可写访问选项...
static class ServicesCollectionExtensions
{
public static void ConfigureWritable<T>(
this IServiceCollection services,
IConfigurationRoot configuration,
string sectionName,
string file) where T : class, new()
{
services.Configure<T>(configuration.GetSection(sectionName));
services.AddTransient<IWritableOptions<T>>(provider =>
{
var environment = provider.GetService<IHostingEnvironment>();
var options = provider.GetService<IOptionsMonitor<T>>();
IOptionsWriter writer = new OptionsWriter(environment, configuration, file);
return new WritableOptions<T>(sectionName, writer, options);
});
}
}
可以在ConfigureServices
等一起使用......
services.ConfigureWritable<CustomizableOptions>(this.Configuration,
"MySection", "appsettings.custom.json");
在我Controller
CL屁股我可以只需要一个IWritableOptions<CustomizableOptions>
实例,它具有与IOptions<T>
相同的特性,但也允许更改和存储配置值。
private IWritableOptions<CustomizableOptions> options;
...
this.options.Update((opt) => {
opt.SampleOption = "...";
});
非常感谢。我有关于['IConfigurationRoot']的后续问题(https://stackoverflow.com/questions/48939567/how-to-access-iconfigurationroot-in-startup-on-net-core-2),也许你知道回答:) –
简体版Matze的回答:
public interface IWritableOptions<out T> : IOptionsSnapshot<T> where T : class, new()
{
void Update(Action<T> applyChanges);
}
public class WritableOptions<T> : IWritableOptions<T> where T : class, new()
{
private readonly IHostingEnvironment _environment;
private readonly IOptionsMonitor<T> _options;
private readonly string _section;
private readonly string _file;
public WritableOptions(
IHostingEnvironment environment,
IOptionsMonitor<T> options,
string section,
string file)
{
_environment = environment;
_options = options;
_section = section;
_file = file;
}
public T Value => _options.CurrentValue;
public T Get(string name) => _options.Get(name);
public void Update(Action<T> applyChanges)
{
var fileProvider = _environment.ContentRootFileProvider;
var fileInfo = fileProvider.GetFileInfo(_file);
var physicalPath = fileInfo.PhysicalPath;
var jObject = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(physicalPath));
var sectionObject = jObject.TryGetValue(_section, out JToken section) ?
JsonConvert.DeserializeObject<T>(section.ToString()) : (Value ?? new T());
applyChanges(sectionObject);
jObject[_section] = JObject.Parse(JsonConvert.SerializeObject(sectionObject));
File.WriteAllText(physicalPath, JsonConvert.SerializeObject(jObject, Formatting.Indented));
}
}
public static class ServiceCollectionExtensions
{
public static void ConfigureWritable<T>(
this IServiceCollection services,
IConfigurationSection section,
string file = "appsettings.json") where T : class, new()
{
services.Configure<T>(section);
services.AddTransient<IWritableOptions<T>>(provider =>
{
var environment = provider.GetService<IHostingEnvironment>();
var options = provider.GetService<IOptionsMonitor<T>>();
return new WritableOptions<T>(environment, options, section.Key, file);
});
}
}
用法:
services.ConfigureWritable<MyOptions>(Configuration.GetSection("MySection"));
然后:
private readonly IWritableOptions<MyOptions> _options;
public MyClass(IWritableOptions<MyOptions> options)
{
_options = options;
}
要更改保存到文件:
_options.Update(opt => {
opt.Field1 = "value1";
opt.Field2 = "value2";
});
而且你可以通过自定义的JSON文件作为可选参数(它将使用appsettings.json默认):
services.ConfigureWritable<MyOptions>(Configuration.GetSection("MySection"), "appsettings.custom.json");
框架提供用于读取配置值,通用的基础设施,而不是对其进行修改。在修改时,您必须使用特定的配置提供程序来访问和修改底层配置源。 – haim770
“访问和修改底层配置源的特定配置提供程序”?请给我一些参考资料,以开始? – 439
你打算修改的配置来源是什么? – haim770