How can I share config file like appsettings.json across multiple ASP.NET CORE projects in one solution in Visual Studio 2015?
Solution 1
You can use absolute path on each project like this(I assume appsettings.json
file is in the solution root directory(like global.json) ):
var settingPath = Path.GetFullPath(Path.Combine(@"../../appsettings.json")); // get absolute path
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile(settingPath);
see https://github.com/aspnet/Configuration/issues/440
Solution 2
Another option is to use user secrets and have the apps share the same app id.
As a bonus, you get the keep the connection strings outside of your app and decrease the chances that they will leak because they were pushed in source control.
Solution 3
Set the absolute path to the shared appsettings.json file.
var relativePath = @"../../The/Relative/Path";
var absolutePath = System.IO.Path.GetFullPath(relativePath);
Then use a IFileProvider
like this.
var fileProvider =
new Microsoft.Extensions.FileProviders.PhysicalFileProvider(absolutePath);
_configuration = new ConfigurationBuilder()
.SetBasePath(_env.ContentRootPath)
.AddJsonFile(fileProvider, $"appsettings.json", optional: true, reloadOnChange: true)
.Build();
Or use SetBasePath
like this.
var relativePath = @"../../The/Relative/Path";
var absolutePath = System.IO.Path.GetFullPath(relativePath);
_configuration = new ConfigurationBuilder()
.SetBasePath(absolutePath)
.AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true)
.Build();
Both will work, though the file provider approach allows the app to use its content root as the base path for other static content. Adem's approach is also good.
Solution 4
There may be a better way to do this, but you could achieve this by adding a precompile setting to the project.json file. Something similar to:
"scripts": {
"precompile": [ "../copycommand.bat" ]
}
Where the copycommand
points to a batch command that copies your AppSettings.json file into the current directory. If you're targeting multiple platforms, you'll likely need to customise the command for each of the platforms.
Solution 5
Add a shared project containing the appsettings.json files set to 'Copy if newer' and reference from the other projects.
jump4791
Updated on June 18, 2022Comments
-
jump4791 almost 2 years
I have 3 ASP.NET CORE projects in one solution and I want to share connection string information in one config file like appsettings.json across these projects.
How can I do this in Visual Studio 2015 ?
-
Yahoo Serious over 4 yearsAndrew Lock has a work around to also publish your shared settings.
-
Armin Shoeibi over 2 yearsthis solution is not working in .NET 6 RC 2