asp.net core TestServer 找不到配置

Raf*_*aeu 2 c# web-hosting asp.net-core

我正在使用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); 
Run Code Online (Sandbox Code Playgroud)

在我的“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();
}
Run Code Online (Sandbox Code Playgroud)

当我调用Configuration.GetConnectionString("") 时,它会抛出一个异常,如果我进一步检查,我可以看到实际上没有加载任何配置。可能是与相对/绝对路径相关的问题.UseContentRoot(Directory.GetCurrentDirectory())

HEx*_*xit 5

在测试环境中,

.SetBasePath(env.ContentRootPath)
Run Code Online (Sandbox Code Playgroud)

env.ContentRootPath 与生产不同,如果我没记错的话,它被设置为测试项目的 bin 目录。因此,它不会找到 appsettings.json 文件。除非您在构建后将其复制到那里。

如果你是项目文件夹结构不会改变。您可以尝试将这两行中的 appsettings.json" 路径硬编码到它们所在的位置。

.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true
Run Code Online (Sandbox Code Playgroud)

如果这有效(应该),您可以通过在代码中找到 appsetting.json 路径来改进它。

以下是我自己在测试环境中工作的代码。

        var settingFilePath = getSettingFilePath(settingFileParentFolderName: "APIProject");

        var builder = new ConfigurationBuilder()
            .AddJsonFile(settingFilePath + _settingFileName, optional: true, reloadOnChange: true)
            .AddJsonFile(settingFilePath + "appsettings.Development.json", optional: true);

        var configuration = builder.Build();
Run Code Online (Sandbox Code Playgroud)

getSettingFilePath() 只是一个在启动项目文件夹中定位设置文件路径的函数。

希望这有帮助。