How to read appSettings JSON from Class Library in ASP.NET Core

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

configuration-nuget-packages

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

 

Anuncios

Un comentario en “How to read appSettings JSON from Class Library in ASP.NET Core

¿Quieres agregar algo?

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión /  Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión /  Cambiar )

Conectando a %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.