ASP.NET Core 应用程序的自定义设置可以存储在不同的位置,以下是几种常用的解决方法。
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var settingValue = configuration["SettingKey"];
var settingValue = Environment.GetEnvironmentVariable("SettingKey");
var commandLineArgs = Environment.GetCommandLineArgs();
var settingValue = commandLineArgs.FirstOrDefault(arg => arg.StartsWith("--SettingKey="))?.Split('=')[1];
public class CustomConfigurationProvider : ConfigurationProvider
{
public override void Load()
{
// 从自定义存储位置加载设置
var settingValue = LoadSettingFromCustomStore("SettingKey");
Data.Add("SettingKey", settingValue);
}
private string LoadSettingFromCustomStore(string key)
{
// 从自定义存储位置加载指定键的设置值
// 实现自己的逻辑
return settingValue;
}
}
public class CustomConfigurationSource : IConfigurationSource
{
public IConfigurationProvider Build(IConfigurationBuilder builder)
{
return new CustomConfigurationProvider();
}
}
然后,可以在 Startup.cs
中使用自定义配置提供程序:
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
}
public void ConfigureServices(IServiceCollection services)
{
// 注册自定义配置提供程序
services.AddSingleton(new CustomConfigurationSource());
services.AddSingleton(provider => new ConfigurationRoot(new List
{
provider.GetService().Build(provider)
}));
}
}
以上是几种常见的解决方法,根据具体的需求和应用场景,可以选择适合的方式存储和读取自定义设置。