i have a problem with appsettings reading.
I have project1 with appsettings.json
in it. I want to use the same appsettings.json
in project2. I added this lines of code in 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:
In project i can see it as expected:
But when i try to run project2
i am getting error, that Uri
is not found:
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddAzureKeyVault(new Uri(builder.Configuration["KeyVault:Uri"]), new DefaultAzureCredential());
When i tried to read appsettings.json
manually:
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. Linking files worked in .NET Core 3.1
How to read linked appsettings.json
in second project in .NET6
? It seems like something changed from Core to .NET.
CodePudding user response:
You need to use Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
to get path to build directory, not 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. Put it to 3rd folder shared
(or something like that), and reference it by link in both projects.