Net Core:Startup.Cs 中 .SetBasePath 和 .UseContentRoot 的区别

5 c# .net-core asp.net-core

启动配置中的 .SetBasePath 和 .UseContentRoot 有什么区别?

var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();
Run Code Online (Sandbox Code Playgroud)

如何在集成测试中使用 IConfiguration?

Kir*_*kin 5

SetBasePath是 的扩展方法IConfigurationBuilder,它设置定位配置文件时使用的路径:

将基于文件的提供程序的 FileProvider 设置为具有基本路径的 PhysicalFileProvider。

例如,在定位appsettings.json您在问题中指定的文件时,它将在使用检索的路径中查找Directory.GetCurrentDirectory()

UseContentRoot是 的扩展方法IWebHostBuilder,它contentRoot为 Web 主机设置密钥:

此设置确定 ASP.NET Core 从何处开始搜索内容文件,例如 MVC 视图。

用于contentRoot密钥的默认值为:

[...] 应用程序集所在的文件夹。

这意味着,对于典型设置,两者的路径最终将相同,但这不是必需的。