简体   繁体   English

.NET 6 应用程序未读取链接的 appsettings.json

[英].NET 6 application is not reading linked appsettings.json

i have a problem with appsettings reading.我在阅读 appsettings 时遇到问题。

I have project1 with appsettings.json in it.我有带有appsettings.json的 project1。 I want to use the same appsettings.json in project2.我想在 project2 中使用相同的appsettings.json I added this lines of code in project2.csproj :我在project2.csproj中添加了这行代码:

    <ItemGroup>
        <Content Include="../project1/appsettings.json">
            <Link>appsettings.json</Link>
            <CopyToOutputDirectory>Always</CopyToOutputDirectory>
        </Content>
    </ItemGroup>

And it do his job, appsettings.json is copied to Debug directory:它完成了他的工作, appsettings.json复制到Debug目录:

在此处输入图像描述

In project i can see it as expected:在项目中,我可以按预期看到它:

在此处输入图像描述

But when i try to run project2 i am getting error, that Uri is not found:但是当我尝试运行project2时出现错误,找不到Uri

var builder = WebApplication.CreateBuilder(args);

builder.Configuration.AddAzureKeyVault(new Uri(builder.Configuration["KeyVault:Uri"]), new DefaultAzureCredential());

When i tried to read appsettings.json manually:当我尝试手动阅读appsettings.json时:

builder.Configuration
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", false, true)
    .Build();

I get error, that appsettings.json is not exist in root folder (where Program.cs is placed), not in Debug folder.我收到错误, appsettings.json不在根文件夹(放置Program.cs的位置)中,不在Debug文件夹中。 Linking files worked in .NET Core 3.1在 .NET Core 3.1 中工作的链接文件

How to read linked appsettings.json in second project in .NET6 ?如何在appsettings.json的第二个项目中读取链接的.NET6 It seems like something changed from Core to .NET.似乎从 Core 更改为 .NET。

You need to use Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) to get path to build directory, not Directory.GetCurrentDirectory() .您需要使用Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)来获取构建目录的路径,而不是Directory.GetCurrentDirectory() So try this:所以试试这个:

builder.Configuration
    .SetBasePath(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))
    .AddJsonFile("appsettings.json", false, true)
    .Build();

Also, if you have shared configuration file between 2 projects, then it would be better to keep it outside project1 folder also.此外,如果您在 2 个项目之间共享配置文件,那么最好将其保存在project1文件夹之外。 Put it to 3rd folder shared (or something like that), and reference it by link in both projects.将其放入shared的第三个文件夹(或类似的文件夹),并通过两个项目中的链接引用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM