Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 769
jump4791 Avatar asked Jul 09 '16 21:07

jump4791


People also ask

Can we have more than one appSettings json?

Of course, we can add and use multiple appsettings. json files in ASP.NET Core project. To configure and read data from your custom json files, you can refer to the following code snippet. Host.

How do I add appSettings json to project?

Add Json File After adding the file, right click on appsettings. json and select properties. Then set “Copy to Ouptut Directory” option to Copy Always. Add few settings to json file, so that you can verify that those settings are loaded.

How can I get the connection string from appSettings json in NET Core in class library?

We simply need to inject a dependency Constructor with the Startup class for reading the values. With . NET Core, we can use IServiceCollection as single tone object or more specifically a configuration interface IConfiguration for reading JSON key value in our code.


2 Answers

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

like image 181
adem caglin Avatar answered Sep 19 '22 11:09

adem caglin


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.

like image 36
Victor Hurdugaci Avatar answered Sep 22 '22 11:09

Victor Hurdugaci