ASP.NET Core的TestServer无法找到配置。

4

我正在使用 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()) 相对/绝对路径的问题有关。

不是因为在生产环境中工作,我们甚至没有一个web.config文件... - Raffaeu
1
@RamSingh:你错了,因为在ASP.NET Core中没有使用web.config进行配置,而是使用IConfiguration从配置中读取配置设置(可以是基于文件的json、环境变量或命令行参数,具体取决于在ConfigurationBuilder()调用期间插入哪些提供程序)。 - Tseng
2
我认为你的测试 Web 主机生成器有冗余的东西 - 你在 .UseConfiguration(config)MockLicenseStartup 中都指定了配置两次(删除第一个)。此外,你可以省略 .UseKestrel().UseContentRoot(Directory.GetCurrentDirectory()).UseIISIntegration() - Aleksey L.
我已经尝试过了,但似乎编译器没有在输出目录中“复制”JSON文件,这是关于我的测试的FileNotFoundException: The configuration file &#x27;appsettings.json&#x27; was not found and is not optional. - Raffaeu
看起来这是当前的解决方案:https://dev59.com/EZLea4cB1Zd3GeqP46fF - Raffaeu
1个回答

5

在测试环境中,

.SetBasePath(env.ContentRootPath)

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

如果您的项目文件夹结构没有更改,则可以尝试在这两行中硬编码"appsettings.json"路径到它们所在的位置。

.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true

如果这个方法能够正常运行(应该是可以的),你可以通过在代码中查找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();

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

希望这可以帮到您。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接