简体   繁体   中英

How can I share config file like appsettings.json across multiple ASP.NET CORE projects in one solution in Visual Studio 2015?

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 ?

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

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.

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.

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.

添加一个包含 appsettings.json 文件的共享项目,该文件设置为“如果较新则复制”并从其他项目中引用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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