Hi, in this post we’ll show you how to read the appSettings.json file in your ASP.NET Core application from another library.
First
Having both projects, we proceed to add the following NuGet packages to the class library:
– Microsoft.Extensions.Configuration
– Microsoft.Extensions.Configuration.Abstractions (this will be installed anyways)
– Microsoft.Extensions.Configuration.Json
Second
Let’s edit your appsettings.json file adding a ConnectionString and a section with one value:
{ "ConnectionStrings": { "DataConnection": "Server=.;Database=AppStore;Trusted_Connection=True;MultipleActiveResultSets=true;Integrated Security=True;" }, "ApplicationSettings": { "Sample": "sample-text-yay!" } }
Third
Create a class for managing the reads, let’s say ‘AppConfiguration‘ and create your ConfigurationBuilder adding a JSON file as IConfigurationSource:
var configurationBuilder = new ConfigurationBuilder(); var path = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json"); configurationBuilder.AddJsonFile(path, false); ... public class AppConfiguration : IAppConfiguration { private readonly string _sqlConnection; private readonly string _sample; public AppConfiguration() { var configurationBuilder = new ConfigurationBuilder(); var path = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json"); configurationBuilder.AddJsonFile(path, false); var root = configurationBuilder.Build(); _sqlConnection = root.GetConnectionString("DataConnection"); var appSetting = root.GetSection("ApplicationSettings"); var test = appSetting["Sample"]; } public string SqlDataConnection { get => _sqlConnection; } public string Sample { get => _sample; } }
If you have problems when executing or deploying the app, probably the app is missing his configuration file.
1.- Check the Path you’re reading in the AppConfiguration
2.- Add the following code to your project.json file in the Core app:
"buildOptions": { "copyToOutput": { "include": [ "appsettings.json" ] }
Then the app builder will always copy the file.
References
- ASP.NET Docs – Configuration, https://docs.asp.net/en/latest/fundamentals/configuration.html
- ASP.NET 5 Configuration – Microsoft Framework ConfigurationModel, https://blog.jsinh.in/asp-net-5-configuration-microsoft-framework-configurationmodel/#.WAuoE32jgZ8