我的 Web 应用程序需要从 appsettings.json 文件中读取文档数据库键。我创建了一个带有键名的类并阅读了 ConfigureServices()
中的配置部分如:
public Startup(IHostingEnvironment env) {
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services) {
services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
services.AddSession();
Helpers.GetConfigurationSettings(services, Configuration);
DIBuilder.AddDependency(services, Configuration);
}
我正在寻找读取测试项目中关键值的方法。
最佳答案
这是基于博客文章 Using Configuration files in .NET Core Unit Test Projects (为 .NET Core 1.0 编写)。
appsettings.test.json
)最好与正常的 appsettings.json
不同,因为如果将使用相同的名称,则主项目中的文件可能会覆盖测试项目中的文件。 public static IConfiguration InitConfiguration()
{
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.test.json")
.Build();
return config;
}
var config = InitConfiguration();
var clientId = config["CLIENT_ID"]
顺便说一句:您也可能对将配置读入 IOptions 类感兴趣,如 Integration test with IOptions<> in .NET Core 中所述。 :
var options = config.Get<MySettings>();
关于c# - 读取 .NET Core 测试项目中的 appsettings json 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39791634/