Reading appsettings.json from .net standard library

Lollo picture Lollo · May 28, 2018 · Viewed 12.4k times · Source

i have started a new RESTful project using .NET Core Framework.

I divided my solution in two parts: Framework (set of .NET standard libraries) and Web (RESTful project).

With Framework folder i provide some of library for furthers web project and into one of these i'd like to provide a Configuration class with the generic method T GetAppSetting<T>(string Key).

My question is: how can i get the access to the AppSettings.json file in .NET Standard?

I have found so many example about reading this file, but all these examples read the file into the web project and no-one do this into an extarnal library. I need it to have reusable code for Others project.

Answer

Bruno Zell picture Bruno Zell · May 28, 2018

As already mentioned in the comments, you really shouldn't do it. Inject a configured IOptions<MyOptions> using dependency injection instead.

However, you can still load a json file as configuration:

IConfiguration configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory()) // Directory where the json files are located
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .Build();

// Use configuration as in every web project
var myOptions = configuration.GetSection("MyOptions").Get<MyOptions>();

Make sure to reference the Microsoft.Extensions.Configuration and Microsoft.Extensions.Configuration.Json packages. For more configuration options see the documentation.