多项目场景下.NET Core 2.1.103 WebAPI的appsettings.json位置问询
嘿,针对你这个.NET Core 2.1.103多项目WebAPI的配置场景,我正好有不少实践经验,给你梳理下最靠谱的配置方案:
首先明确:每个项目的appsettings.json(包括环境变体比如appsettings.Development.json)必须放在项目根目录,也就是:
c:\code\my_big_solution\project1\appsettings.jsonc:\code\my_big_solution\project2\appsettings.json
绝对不要把配置文件直接放在bin\Debug这类输出目录里——因为输出目录是编译生成的临时目录,每次重新编译都会被覆盖,而且版本控制(比如Git)也应该跟踪项目根目录的配置文件,而不是编译产物。
为了让程序运行时能读取到配置文件,你需要在每个项目的.csproj文件里添加以下配置,确保编译时把配置文件复制到输出目录:
<ItemGroup> <!-- 基础配置文件,始终复制 --> <Content Include="appsettings.json"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <!-- 仅Debug环境复制开发配置 --> <Content Include="appsettings.Development.json" Condition="'$(Configuration)'=='Debug'"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <!-- 可以再加Release环境的配置 --> <Content Include="appsettings.Release.json" Condition="'$(Configuration)'=='Release'"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> </ItemGroup>
这样编译后,配置文件会出现在对应项目的bin\Debug\netcoreapp2.1目录下(.NET Core 2.1的标准输出路径),程序运行时能自动识别。
在每个项目的Startup.cs里,.NET Core的默认配置系统已经帮你处理了路径问题,直接注入IConfiguration就能读取:
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { // 示例:读取连接字符串 var connString = Configuration.GetConnectionString("DefaultConnection"); services.AddDbContext<Project1DbContext>(opts => opts.UseSqlServer(connString)); // 其他服务配置... } }
默认情况下,配置系统会按优先级加载:环境变量 > 命令行参数 > 环境特定配置文件 > 基础appsettings.json,完全不需要你硬编码文件路径。
如果有一些全局配置(比如日志、通用API地址)需要多个项目共用,别复制粘贴文件,解决方案根目录放一个appsettings.shared.json,然后在每个项目的配置加载逻辑里引入:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { var env = hostingContext.HostingEnvironment; // 先加载项目自身的配置 config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true) // 加载解决方案根目录的共享配置,路径是相对输出目录的上两级 .AddJsonFile("../../appsettings.shared.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); }) .UseStartup<Startup>();
这里的../../是因为项目输出目录在project1/bin/Debug,上一级是project1,再上一级就是解决方案根目录,这样就能正确读取共享配置了。
内容的提问来源于stack exchange,提问作者Andr

