You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core Web项目无法找到引用的appsettings文件求助

解决.NET Web SDK引用共享类库配置文件的问题

方法1:显式修改配置加载逻辑

在Web项目的Program.cs中,手动指定从程序运行目录(输出目录)加载共享配置文件,确保配置加载器能找到复制后的文件:

var builder = WebApplication.CreateBuilder(args);

// 设置基础路径为程序运行目录,添加共享配置文件
builder.Configuration
    .SetBasePath(AppContext.BaseDirectory)
    .AddJsonFile("global-appsettings.json", optional: false, reloadOnChange: true);

// 后续服务注册及应用构建逻辑
var app = builder.Build();

AppContext.BaseDirectory在调试和发布状态下都会指向正确的输出目录,能稳定找到共享配置文件。

方法2:调整类库与Web项目的文件复制规则

先确保共享类库的.csproj中配置文件的复制规则正确:

<ItemGroup>
  <Content Include="global-appsettings.json">
    <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    <CopyToPublishDirectory>Always</CopyToPublishDirectory>
  </Content>
</ItemGroup>

再在Web项目的.csproj中,确认类库引用的私有属性开启,保证内容文件能被复制到Web项目的输出目录:

<ItemGroup>
  <ProjectReference Include="..\YourSharedLibrary\YourSharedLibrary.csproj">
    <Private>True</Private>
  </ProjectReference>
</ItemGroup>

方法3:通过配置源扩展加载(进阶)

如果需要更灵活的配置管理,可以直接拼接路径添加配置源:

builder.Configuration.AddJsonFile(
    Path.Combine(AppContext.BaseDirectory, "global-appsettings.json"),
    optional: false
);

内容的提问来源于stack exchange,提问作者J.Paravicini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 16:42:06