我正在使用 TestServer 创建一些测试,它是使用以下复杂配置引导的:
var config = new ConfigurationBuilder()
.Build();
webHostBuilder = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.CaptureStartupErrors(true)
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<MockLicenseStartup>()
.UseEnvironment("Development")
.UseUrls("http://locahost");
testServer = new TestServer(webHostBuilder);
在我的“asp.net core”项目和测试项目中,我已经创建了多个appsettings.json文件,用于提供以下内容:
- 连接字符串
- 日志详细程度
- 自定义节
我面临的问题是,我的 MockLicenseStartup 类中的 Configuration 类不能加载任何可用的 appsettings.json 文件。
在 MockLicenseStartup.cs 中使用的代码如下:
public MockLicenseStartup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
当我调用 Configuration.GetConnectionString("") 函数时,会抛出异常。如果我进一步检查,可以发现实际上没有加载任何配置。这可能与
.UseContentRoot(Directory.GetCurrentDirectory())
相对/绝对路径的问题有关。
.UseConfiguration(config)
和MockLicenseStartup
中都指定了配置两次(删除第一个)。此外,你可以省略.UseKestrel()
、.UseContentRoot(Directory.GetCurrentDirectory())
、.UseIISIntegration()
。 - Aleksey L.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional.
- Raffaeu